BinarySearch golang data structures and algorithms of the binary search method

Basic grammar almost,

We need to look at the system line and the data structures and algorithms.

I did not find the right book,

Reference project on github:

https://github.com/floyernick/Data-Structures-and-Algorithms/

Note golang There is no main function, can not be executed,

When testing, you can use the go test.

BinarySearch.go

package BinarySearch

//二分法查找
func BinarySearch(array []int, number int) int {
	minIndex := 0
	maxIndex := len(array) - 1
	for minIndex <= maxIndex {
		midIndex := int((maxIndex + minIndex) / 2)
		midItem := array[midIndex]
		if number == midItem {
			return midIndex
		}

		if midItem < number {
			minIndex = midIndex + 1
		} else if midItem > number {
			maxIndex = midIndex - 1
		}
	}

	return -1
}

  

BinarySearch_test.go

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()))
	fmt.Println(random)
	array := make([]int, random.Intn(100))
	fmt.Println(array)

	for i := range array {
		array[i] = random.INT (100)
	}
	fmt.Println(array)
	SortArray(array)
	fmt.Println(array)

	for _, value := range array {
		result := BinarySearch(array, value)
		if result == -1 {
			t.Fail()
		}
	}
}

  

 

Guess you like

Origin www.cnblogs.com/aguncn/p/11668457.html