Download presentation
Presentation is loading. Please wait.
Published byMarvin Walsh Modified over 9 years ago
1
Binary search
2
What is binary search? We have a sequence of data, sorted by a relation, and an element to search for in the list We would like to decide whether there is any occurence of the given element give the position of the occurence We want do it effectively, quickly, using the order of the sequence
3
Example The sequence sorted increasing Element to search
4
Step I. Searching interval is [1..16] (the whole) We compare the searched element (0) and the middle element of the interval (11) As the searched element (0) is less then the middle element of the interval (11) we continue the searching in the left part of the interval
5
Step II. Actual searching interval is [1..7] We compare the searched element (0) and the middle element of the actual searching interval (-2) As the searched element is greater than the middle element of the interval we continue searching in the right part of the actual searching interval
6
Step III. Actual searching interval is [5..7] We compare the searched element (0) and the middle element of the actual searching interval (4) As the searched element is less than the middle element of the sequence we continue searching in the left part of the actual searching interval
7
Step IV. Actual searching interval is [5..5] We compare the searched element (0) and the „middle element” of the actual searching interval (0) And we find the searched element!
8
Comments It is very quick searching method If the number of elements is N, the maximum steps of the search is log 2 N For example: if number of the elements is 1000000, then we found the searched element in maximum 20 steps.
9
Common data specification of binary search Input data A: Array of BaseType // the sequence we are searching in N:Integer // Number of the sequence K:BaseType // the searched element Output data L:Booelan // True if we found K in A Ind // Position of K in A
10
Algorithm of binary search in pseudo-code Procedure BinarySearch B:=1 // Initialization of variables E:=N L:=False Loop While (B<=E) And Not(L) I:=(B+E) Div 2 // Index of middle element Selection Case (A[I]<K) B:=I+1 // Cont. in the right part Case (A[I]>K) E:=I-1 // Cont. in the left part Case (A[I]=K) Ind:=I // Found L:=True End Selection End Loop End Procedure
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.