The precondition array must be ordered
Defines the minimum, maximum, and median index of a corner label
int Min,max,mid; Min=0; Max=arr.length-1; Mid= (Min+max)/2;
The above index needs to change, using a loop, condition: When the middle value is not equal to the target value
int Min,max,mid; Min=0; Max=arr.length-1; Mid= (Min+max)/2; while (arr[mid]!=key) { if(key<Arr[mid]) { }Elseif (arr[mid]<key) { } }
When the median value is greater than the target value, the maximum angle is moved to the Middle corner label -1 position
When the median value is less than the target value, the minimum angle is moved to the Middle corner label +1 position
The middle angle Mark continues the two points
int Min,max,mid; Min=0; Max=arr.length-1; Mid= (Min+max)/2; while (arr[mid]!=key) { if(key<Arr[mid]) { max=mid-1; } Else if (arr[mid]<key) { min=mid+1; } Mid= (Min+max)/2; } return mid;
There is a problem with the code at this point, when the target is not found, it will fall into a dead loop, plus a judgment
If not found, the minimum angle and the maximum angle bidding clubs dislocation
intMin,max,mid; Min=0; Max=arr.length-1; Mid= (Min+max)/2; while(arr[mid]!=key) { if(key<Arr[mid]) {Max=mid-1; }Else if(arr[mid]<key) {min=mid+1; } if(Min>max)return-1; Mid= (Min+max)/2; } returnMid
Java Edition:
Public classArraydemo {/** * @paramargs*/ Public Static voidMain (string[] args) {int[] arr=New int[]{1,4,6,7,8,9}; System.out.println ("Index:" +keysearch (arr,7));//Index: 3System.out.println ("Index:" +helfsearch (arr,7));//Index: 3 } /*** Two-point search *@paramarr *@paramKey *@return */ Public Static intHelfsearch (int[] arr,intkey) { intMin,max,mid; Min=0; Max=arr.length-1; Mid= (Min+max)/2; while(arr[mid]!=key) { if(key<Arr[mid]) {Max=mid-1; }Else if(arr[mid]<key) {min=mid+1; } if(Min>max)return-1; Mid= (Min+max)/2; } returnmid; } /*** Gets the position where the value first appears in the array *@paramarr *@paramnum *@return */ Public Static intKeysearch (int[] arr,intnum) { for(inti=0;i<arr.length;i++){ if(arr[i]==num) { returni; } } return-1; }}
PHP Version:
<?PHPclassarraydemo{ Public Static functionMain () {$arr=Array(1,4,6,7,8,9); Echo"Index:". Arraydemo::keysearch ($arr, 7);//Index: 3 Echo"Index:". Arraydemo::helfsearch ($arr, 7);//Index: 3 } /** binary search * @param arr * @param key * @return*/ Public Static functionHelfsearch ($arr,$key){ $min=0; $max=Count($arr)-1; $mid=Ceil(($min+$max)/2); while($arr[$mid]!=$key){ if($key<$arr[$mid]){ $max=$mid-1; }Else if($arr[$mid]<$key){ $min=$mid+1; } $mid=Ceil(($min+$max)/2); if($min>$max)return-1; } return $mid; } /** * Gets the position where the value first appears in the array * @param arr * @param num * @return*/ Public Static functionKeysearch ($arr,$key){ for($i= 0;$i<Count($arr);$i++){ if($arr[$i]==$key){ return $i; } } return-1; }}arraydemo:: Main ();
[Javase] Array (Lookup-two-point lookup)