Download presentation
Presentation is loading. Please wait.
1
Binary Search and Intro to Sorting
Intro to Computer Science CS1510 Dr. Sarah Diesburg
2
Last Time We looked at two basic algorithms for searching
Linear search Binary search Linear search was the easiest to write But perhaps not the best from a complexity standpoint
3
Last Time Big “O” measures how badly the problem grows as the data set grows Study of complexity of algorithms Worst case of linear search was N, where N is the number of comparisons that we need to perform Double the number of items in list, double the amount of time needed to complete the search in the worst case
4
Last Time The binary search was another solution that incurred less comparisons in the worst case Only works on sorted list
5
Binary Search Binary search algorithm
Try the guess at middle index of the range If the value we are searching for is higher than number at the index, then adjust your low range bound to be your guess+1 If the value we are searching for is lower than number at the index, then adjust your high range bound to be your guess-1 Repeat
6
Binary Search What is the worst-case scenario of the binary search?
Thinking of a number between 1 and 100 7 guesses in total – why? 1 guesses – cut down to 50 possibilities 2 guesses – cut down to 25 3 guesses – cut down to 12 4 guesses – cut down to 6 5 guesses – cut down to 3 6 guesses – cut down to 1 7 guesses – to figure out if last guess is right
7
Binary Search What is the complexity of a binary search? log2(100) = x
Big O value of log2 N This is “log base 2” log2(100) = x What is this saying?
8
Binary Search What is the complexity of a binary search? log2(100) = x
Big O value of log2 N This is “log base 2” log2(100) = x What is this saying? 2x = 100 Go “to the next power” when not exact
9
Binary Search How does that relate to our binary search?
Let’s say there are 16 items in our list. What is the worst case number of guesses? 32? 34? 64? One million?
10
Binary Search How does that relate to our binary search?
Let’s say there are 16 items in our list. What is the worst case number of guesses? 32? 34? 64? One million? One million is about 20 guesses 2^10 = 1024 One million is 1000 squared, so twice as much
11
Searching So which kind of search would amazon.com use to search their databases?
12
Demo binarySearch() on different types of lists Ordered Odd Reverse
13
Demo binarySearch() on different types of lists
Ordered Odd Reverse The reverse list doesn’t work because the list needs to be sorted in ascending order. How do we sort?
14
Intro to Sorting Let’s watch a quick video
How can we know which sort is really faster? Bubble Sort Insertion Sort Quick Sort We need to use Big “O” analysis (next time…)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.