github.com/Nigel2392/go-datastructures@v1.1.5/binarysearch/binarysearch.go (about)

     1  package binarysearch
     2  
     3  import (
     4  	"math"
     5  
     6  	"github.com/Nigel2392/go-datastructures"
     7  )
     8  
     9  type lt[T datastructures.Ordered] struct {
    10  	Val T
    11  }
    12  
    13  func (lt lt[T]) Lt(val T) bool {
    14  	return lt.Val < val
    15  }
    16  
    17  func MakeComparableSlice[T datastructures.Ordered](arr []T) []datastructures.Comparable[T] {
    18  	var newArr = make([]datastructures.Comparable[T], len(arr))
    19  	for i, v := range arr {
    20  		newArr[i] = lt[T]{Val: v}
    21  	}
    22  	return newArr
    23  }
    24  
    25  func Search[T datastructures.Comparable[T]](arr []T, val T) int {
    26  	return findTarget(arr, val, 0, len(arr)-1)
    27  }
    28  
    29  func findTarget[T datastructures.Comparable[T]](arr []T, val T, start, end int) int {
    30  	if start > end {
    31  		return -1
    32  	}
    33  
    34  	var mid = int(math.Floor(float64(start+end) / 2))
    35  	if !arr[mid].Lt(val) && !val.Lt(arr[mid]) {
    36  		return mid
    37  	}
    38  	if val.Lt(arr[mid]) {
    39  		return findTarget(arr, val, start, mid-1)
    40  	}
    41  	if arr[mid].Lt(val) {
    42  		return findTarget(arr, val, mid+1, end)
    43  	}
    44  	return -1
    45  }