Presentation is loading. Please wait.

Presentation is loading. Please wait.

BINARY SEARCH ALGORITHM

Similar presentations


Presentation on theme: "BINARY SEARCH ALGORITHM"— Presentation transcript:

1 BINARY SEARCH ALGORITHM
This only applies to a list of names in alphabetical order or a list of numbers in increasing order. Unordered lists would have a sorting algorithm applied first. This algorithm concentrates on the midpoint of an ever reducing list. We define the midpoint of a list of N names, numbered N1, N1+1,...,N2 as [(N1+N2)/2] where [x] = the smallest integer greater than or equal to x We wish to search the list for a name, Fred, say.

2 Step 1 The algorithm compares Fred with the middle name in the list. Either a) the name Fred is found to be at this position, or b) the name Fred occurs before the middle of the list or c) the name Fred occurs after the middle of the list Step 2 If a) occurs, the search is over. If b) occurs, the search continues with Step 1 on a reduced list consisting of those names before the middle name. If c) occurs, the search continues with Step 1 on a reduced list consisting of those names after the middle name. Stop when Fred has been found or when it has been shown that Fred does not appear on the list. At each stage half of the remaining list is discarded (hence the name of the algorithm).

3 1 Bennett 6 Laing 2 Blackstock 3 Brown 4 Ebenezer 5 Fowler 9 Saludo
Find the name Robinson in the list below: Middle name: 1 Bennett 6 Laing 2 Blackstock Robinson is after Laing So delete names 1-6 3 Brown This leaves names 7 to 10 4 Ebenezer Middle name: 5 Fowler 9 Saludo 6 Laing Robinson is before Saludo So delete names 9-10 7 Leung This leaves names 7 to 8 Middle name: 8 Robinson 8 Robinson 9 Saludo has been found! 10 Scadding

4 1 Bennett 6 Laing 2 Blackstock 3 Brown 4 Ebenezer 3 Brown 5 Fowler
Find the name Davis in the list below: Middle name: 1 Bennett 6 Laing 2 Blackstock Davis is before Laing So delete names 6-10 3 Brown This leaves names 1 to 5 Middle name: 4 Ebenezer 3 Brown 5 Fowler Davis is after Brown So delete names 1-3 6 Laing This leaves names 4 and 5 Middle name: 7 Leung 5 Fowler 8 Robinson 9 Saludo Davis is before Fowler So delete name 5 Only one name left (Ebenezer) and it is not Davis 10 Scadding Hence we conclude that Davis is not on the list


Download ppt "BINARY SEARCH ALGORITHM"

Similar presentations


Ads by Google