Binary find the deformation of the algorithm; The front and back end are orderly, the whole disorder
Source: Internet
Author: User
The ' Package Mainimport ("FMT")//is divided into 2, certainly half is ordered by the Func binarysearchdef (data []int, key int, low int, high int) int {if Len (d ATA) = = 0 {return-1}//Note the critical value for low <= high {mid: = low + (high-low)/2fmt. Println (mid) fmt. Println (Data[mid]) if key = = Data[mid] {return mid}//if key is smaller than intermediate value if key < Data[mid] {if key = = Data[low] {return low}// If key is smaller than the median value, but is greater than the value in the low position if key > Data[low] {//If key is smaller than the median value, the value above the low position is larger, and the element between lower and mid is unordered if mid-1 >= low & ;& Data[low] >= data[mid-1] {return binarysearchdef (data, key, Low, mid-1)}//orderly reverse the other half high = Mid-1}if key < da Ta[low] {if mid-1 >= low && Data[low] >= data[mid-1] {return binarysearchdef (data, key, Low, mid-1)}low = mi D + 1}}if key > Data[mid] {if key = = Data[high] {return high}if key > Data[high] {if mid+1 <= high && dat A[MID+1] >= Data[high] {return binarysearchdef (data, key, mid+1, high)}//in order to reverse the other half, because there must be no corresponding value in the section high = Mid-1}if key < Data[high] {if mid+1 <= high && data[mid+1] >= Data[high] {return binarysearchdef (data, key, mid+1, high)}low = mid + 1}}}return-1}func Main () {data: = [] INT{100, 102, 104, 106, 108, 2, 118, 121, 122, 1,, 3, 4, 5, 6, 7, 8, 9, 10}i: = Binarysearchdef (da TA, 3, 0, Len (data)-1) fmt. Println (i)} "90 reads
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service