Monday 10 February 2020

Binary Search (1)

For Example, the data is:
The key is 6

Record[1][2][3][4][5]
Data252116

First step: the data must be sorting. This sample, we can sort the data with bubble sort methods.

Record[1][2][3][4][5]
Data252116
Step 12521162 and 5, no Exchange
2521162 and 21, no Exchange
1521262 and 1, Exchange 
Step 21521265 and 21, no Exchange
1221562 and 5, Exchange
Step 31252165 and 21, Exchange
Step 412562121 and 6, Exchange
Second step: we can search data key 6 with binary search

New data:

Record [1][2][3][4][5]
Data125621


Step [1]:
                (low+high) div 2 =  (1+5) div 2
                                            =  6 div 2
                                            =  3---> middle
                the data on the record [3] is 5, then 5<6, next step swipe right


lowmiddlehigh
Record [1][2][3][4][5]
Data125621

Step [2]:  new_low = middle +1 = 3 +1 = 4
new_lowhigh
Record[1][2][3][4][5]
Data125621
                 
               (new_low + high) = (4+5) div 2
                                             = 9 div 2
                                             = 4
                the data on the record [4] is 6, then 6=6 , end.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.