美文网首页
BinarySearch

BinarySearch

作者: bocsoft | 来源:发表于2018-11-19 16:36 被阅读0次
    package BinarySearch
    
    func BinarySearch(array []int, number int) int {
        minIndex := 0
        maxIndex := len(array) - 1
    
        for minIndex <= maxIndex {
            midIndex := int((minIndex + maxIndex) / 2)
            midItem := array[midIndex]
            if number == midItem {
                return midItem
            }
            if midItem < number {
                minIndex = midIndex + 1
            } else if midItem > number {
                maxIndex = midIndex - 1
            }
    
        }
        return -1
    }
    
    
    package BinarySearch
    
    import (
        "fmt"
        "math/rand"
        "testing"
        "time"
    )
    
    func SortArray(array []int) {
        for itemIndex, itemValue := range array {
            for itemIndex != 0 && array[itemIndex-1] > itemValue {
                array[itemIndex] = array[itemIndex-1]
                itemIndex -= 1
            }
            array[itemIndex] = itemValue
        }
    
    }
    
    func TestBinarySearch(t *testing.T) {
        random := rand.New(rand.NewSource(time.Now().UnixNano()))
        array := make([]int, random.Intn(100-10)+10)
        for i := range array {
            array[i] = random.Intn(100)
        }
        SortArray(array)
    
        fmt.Println("array:", array)
    
        for _, value := range array {
            result := BinarySearch(array, value)
            fmt.Println("binarySearch value :", result)
            if result == -1 {
                t.Fail()
            }
        }
    }
    
    
    

    相关文章

      网友评论

          本文标题:BinarySearch

          本文链接:https://www.haomeiwen.com/subject/gzjafqtx.html