Algorithms — Search — Fast Linear Search

A Fast Linear Search algorithm enhances the basic linear search by reducing the number of comparisons in scenarios where the element is likely found earlier. One way to potentially speed up a linear search is by searching from both ends of the list simultaneously, often called a bidirectional linear search. This method can be particularly efficient if the target is likely to be closer to the beginning or the end of the list.

Here is an example of how you might implement a fast linear search in Go for a slice of integers:

package main

import (
	"fmt"
)

// fastLinearSearch performs a bidirectional linear search on a slice `data` looking for `target`.
// Returns the index of `target` if found, otherwise returns -1.
func fastLinearSearch(data []int, target int) int {
	front := 0
	back := len(data) - 1

	for front <= back {
		if data[front] == target {
			return front
		}
		if data[back] == target {
			return back
		}
		front++
		back--
	}
	return -1
}

func main() {
	data := []int{10, 22, 35, 40, 55, 60, 75, 85, 90}
	target := 55
	result := fastLinearSearch(data, target)

	if result != -1 {
		fmt.Printf("Element %d found at index %d\\\\n", target, result)
	} else {
		fmt.Println("Element not found")
	}
}

Explanation

This approach reduces the number of iterations needed in the best and average case scenarios, especially when the element is closer to either end of the array. It's a simple enhancement but can provide efficiency improvements in specific scenarios. If you need further adjustments or have another type of data to search through, feel free to ask! 💡

Algorithms — Search — Binary Search

Certainly! Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed the possible locations to just one.

Here’s a basic example of how you might implement binary search in Go for a sorted slice of integers:

package main

import (
	"fmt"
)

// binarySearch performs a binary search on a sorted slice `data` looking for `target`
// Returns the index of `target` if found, otherwise returns -1
func binarySearch(data []int, target int) int {
	low := 0
	high := len(data) - 1

	for low <= high {
		mid := low + (high-low)/2 // This helps prevent overflow in other languages
		midValue := data[mid]

		if midValue == target {
			return mid
		} else if midValue < target {
			low = mid + 1
		} else {
			high = mid - 1
		}
	}
	return -1
}

func main() {
	data := []int{2, 3, 4, 10, 15, 18, 23, 34, 45, 56, 67, 78, 89}
	target := 34
	result := binarySearch(data, target)

	if result != -1 {
		fmt.Printf("Element %d found at index %d\\\\n", target, result)
	} else {
		fmt.Println("Element not found")
	}
}

Explanation