Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sorting and Searching. Searching List of numbers (5, 9, 2, 6, 3, 4, 8) Find 3 and tell me where it was.

Similar presentations


Presentation on theme: "Sorting and Searching. Searching List of numbers (5, 9, 2, 6, 3, 4, 8) Find 3 and tell me where it was."— Presentation transcript:

1 Sorting and Searching

2 Searching List of numbers (5, 9, 2, 6, 3, 4, 8) Find 3 and tell me where it was

3 Linear Search Start at the beginning and search until you find the item What is the algorithm?

4 Linear Search Start at the beginning and search until you find the item What is the algorithm? 1.Set current element to first element 2.Compare target and current element 3.if found – success! 4.else – set current element to be next element 5.go back to step 2

5 Linear Search In the worst case, how many comparisons will you perform?

6 Linear Search In the worst case, how many comparisons will you perform? –N where N is the number of items in the list

7 Binary Search If the list is sorted, can we find a better algorithm? (5, 9, 2, 6, 3, 4, 8) (2, 3, 4, 5, 6, 8, 9) What is the algorithm?

8 Binary Search (2, 3, 4, 5, 6, 8, 9) 1.compare item to middle element 2.if no match, divide list in half 3.if item is less than middle 1.search first half of list 4.else 1.search second half of list 5.go back to 1

9 Binary Search In the worst case, how many comparisons will you perform? –log N where N is the number of items in the list Which is better, linear or binary search? Why?

10 Sorting How would you sort a list of numbers? (5, 3, 1, 6, 9, 4, 8)

11 Sorting How would you sort a list of numbers? (5, 3, 1, 6, 9, 4, 8) cur_index = 0 for each element in list –linear search for smallest element in list starting at cur_index –if smallest element found is less than element at cur_index – swap –increment cur_index

12 Sorting (5, 3, 1, 6, 9, 4, 8) cur_index = 0 min_index = 2 (element 1) swap 0 th element and 2 nd element (1, 3, 5, 6, 9, 4, 8) cur_index = 1

13 Sorting (5, 3, 1, 6, 9, 4, 8) cur_index = 0 swap 0 and 2 (1, 3, 5, 6, 9, 4, 8) cur_index = 1 no swap (1, 3, 5, 6, 9, 4, 8) cur_index = 2 swap 2 and 5 (1, 3, 4, 6, 9, 5, 8) cur_index = 3 swap 3 and 5 (1, 3, 4, 5, 9, 6, 8) cur_index = 4 swap 4 and 5 (1, 3, 4, 5, 6, 9, 8) cur_index = 5 swap 5 and 6 (1, 3, 4, 5, 6, 8, 9) cur_index = 6

14 Complexity of Selection Sort How many comparisons were necessary for selection sort?


Download ppt "Sorting and Searching. Searching List of numbers (5, 9, 2, 6, 3, 4, 8) Find 3 and tell me where it was."

Similar presentations


Ads by Google