Two-point lookup is also called binary lookup.
The premise: the array is ordered.
Thought: 1, each time take the middle number of key to compare, if equal, find;
2, if key > middle number, indicating that key is on the right side of the middle number, then the right side of the middle number and key comparison;
3, if key < Middle number, indicating that key is on the left side of the middle number, and then take the left of the middle number and key comparison;
4, cycle the above process;
Don't say anything, on the code:
1#include <stdio.h>2 3 intMainintargcConst Char*argv[]) {4 5 //Defining Arrays6 intArr[] = {Ten, $, the, the, -,122,456,789,999};7 8 //Find 789 subscript in this array9 intKey =789;Ten One intLen =sizeof(arr)/sizeof(arr[0]); A - intMinindex =0; - intMaxindex = Len-1; the intMiddleindex = len/2;//Subscript of the middle number - - //determine if the middle number equals key - if(Key = =Arr[middleindex]) { +printf"The key ' s index is%d", Middleindex); - return 0; + } A at //if not equal, size is judged - while(Key! =Arr[middleindex]) { - if(Key < Arr[middleindex]) {//Note Key is on the left of the middle number -Maxindex = Middleindex-1;//maximum subscript to the subscript of the previous element of the intermediate number subscript - } - Else if(Arr[middleindex < key]) {//Note Key is on the right of the middle number inMinindex = Middleindex +1;//The minimum subscript changes to the subscript of an element after the middle number of the underlying - } to Else{//Description key = Arr[middleindex] +printf"The key ' s index is%d", Middleindex); - return 0; the } *Middleindex = (Minindex + maxindex)/2; $ }Panax Notoginseng -printf"the number to find is not found"); the + return 0; A}
Binary Find/binary find