search

package
v0.12.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 2, 2024 License: MIT Imports: 0 Imported by: 0

Documentation

Overview

Package search is a simple package that demonstrates various search algorithms.

Included in this package is:

binary search (for loop implementation)
binary search (recursion implementation)
linear search

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func BinaryLoop

func BinaryLoop(xi []int, target int) (index int, ok bool)

BinaryLoop is an algorithm that uses the binary search method to search a given slice. We are expecting a sorted slice, otherwise the result will not be accurate.

https://goplay.space/#TQBxLBIrt-w

https://play.golang.org/p/TQBxLBIrt-w

Example
package main

import (
	"fmt"

	"github.com/eng618/go-eng/algo/search"
)

func main() {
	xi := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}

	if v, ok := search.BinaryLoop(xi, 5); ok {
		fmt.Println("Found 5 at index", v)
	}

	if v, ok := search.BinaryLoop(xi, 25); ok {
		fmt.Println("Found 25 at index", v)
	} else {
		fmt.Println("target number no found in slice")
	}
}
Output:

Found 5 at index 4
target number no found in slice

func BinaryRecursion

func BinaryRecursion(xi []int, target int) bool

BinaryRecursion uses the recursion method to call itself, until it determines if the target is present in the slice (which must be sorted).

Example
package main

import (
	"fmt"

	"github.com/eng618/go-eng/algo/search"
)

func main() {
	xi := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
	fmt.Println("5 is in xi =", search.BinaryRecursion(xi, 5))
	fmt.Println("25 is in xi =", search.BinaryRecursion(xi, 25))
}
Output:

5 is in xi = true
25 is in xi = false

func Linear

func Linear(xi []int, target int) bool

Linear is a simple search algorithm to verify if a target element is present in the provided slice. Unlike the binary search, this does not require the input to be sorted prior to running.

On average the complexity of this algorithm is O(n).

Example
package main

import (
	"fmt"

	"github.com/eng618/go-eng/algo/search"
)

func main() {
	exampleOne := search.Linear([]int{1, 3, 5, 7}, 5)
	exampleTwo := search.Linear([]int{1, 3, 5, 7}, 11)

	fmt.Println(exampleOne)
	fmt.Println(exampleTwo)

}
Output:

true
false

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL