d1: binary search. the binary search is the only algorithm you study in d1 that searches through...

5
D1: Binary Search D1: Binary Search

Upload: ralph-carr

Post on 15-Jan-2016

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: D1: Binary Search. The binary search is the only algorithm you study in D1 that searches through data. The idea of the binary search is that once the

D1: Binary SearchD1: Binary Search

Page 2: D1: Binary Search. The binary search is the only algorithm you study in D1 that searches through data. The idea of the binary search is that once the

D1: Binary Search

The binary search is the only algorithm you study in D1 that searches through data.

The idea of the binary search is that once the data is in order, you search for a data item by looking at the middle data item in the list and comparing it to your target. The target will either be that value, be lower than it, or higher than it.

If the selected value is not your target, you discard it and half the items in the list. Then look through half the data instead. Repeat the process on the smaller list until you find the data item or discover that it is not there.

Page 3: D1: Binary Search. The binary search is the only algorithm you study in D1 that searches through data. The idea of the binary search is that once the

D1: Binary Search

Example Castle Dale EllisGreen

Kitts Martyn Sykes

Use the binary search algorithm on the list above to try to locate the names

a) ‘Dale’ and

b) ‘Phillips’.

WorkingFor a)

C D E G K M S

Green is the middle value. Dale comes before Green, so the list reduces to…

C D E

Dale is the new middle value. Dale is found, second position in the list.

Page 4: D1: Binary Search. The binary search is the only algorithm you study in D1 that searches through data. The idea of the binary search is that once the

D1: Binary Search

Example Castle Dale EllisGreen Kitts Martyn Sykes

Use the binary search algorithm on the list above to try to locate the names

a) ‘Dale’ and

b) ‘Phillips’.

WorkingFor b)

Green is the middle value. Phillips is after Green, so the list reduces to…

C D E G K M S

K M S

Martyn is the new middle value. Phillips is after Martyn, so the list reduces to…

S

Sykes is the last value in the list. This is not Phillips, so you conclude that Phillips is not in the list.

Page 5: D1: Binary Search. The binary search is the only algorithm you study in D1 that searches through data. The idea of the binary search is that once the

D1: Binary Search

Notes

• As with the quick sort, if you have an even number of data items, select the right-most of the middle two as the place to start your search.

• You can have an unsuccessful search. You must still show the steps of the search correctly.

• Some D1 questions start with a sorting algorithm and then ask you to perform a binary search. Be ready!

• Make sure you show changes you make to the list clearly.