sequential lookups do not make any assumptions about the order of the key fields in the table, unlike sequential lookups, where the records in the table are ordered alphabetically by key field, and the following three results appear in the comparison binary:
- searchumn< List[middle].key, you do not need to consider the records between List[middle] and list[n-1], and continue to find records between List[0] and list[middle-1].
- Searchnum=list[middle].key, at this point, the lookup succeeds and ends the lookup.
- Searchnum>list[middle].key, you do not need to consider the records between List[0] and List[middle], and continue to find records between List[middle+1] and list[n-1].
The complexity of time is: O(Lo g n )
Code implementation:
//Comparison functionintCompareintOriginintSearchum) {return(Origin<searchum?-1:(Origin==searchum?0:1));}//Two-way searchintBinsearch (elementList[],intSearchum,intN) {intleft=0, right=n-1, middle; while(Left<=right) {middle= (Right-left)/2+left;Switch(Compare (List[Middle].key,searchum)] { Case-1: left=middle+1; Break; Case 0:returnMiddle; Case 1: right=middle-1; } }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Binary search (binary lookup)