week13

# week13 - Week 13 Searching and Sorting CS 177 1 Searching...

This preview shows pages 1–10. Sign up to view the full content.

CS 177 Week 13: Searching and Sorting 1

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Searching for a number Lets say that I give you a list of numbers, and I ask you, “Is 37 on this list?” As a human, you have no problem answering this question, as long as the list is reasonably short What if the list is an array, and I want you to write a Java program to find some number? 2
Search algorithm Easy! We just look through every element in the array until we find it or run out public static int find( int [] array, int number ) { for ( int i = 0; i < array.length; i++ ) if ( array[i] == number ) return i; 3

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
How long does it take? We talked about Big Oh notation last week Now we have some way to measure how long this algorithm takes How long, if n is the length of the array? O ( n ) time because we have to look through every element in the array, in the worst case 4
Can we do better? Is there any way to go smaller than O ( n )? What complexity classes even exist that are smaller than O ( n )? O (1) O (log n ) Well, on average, we only need to check half the numbers, that’s ½ n which is still O ( n ) 5

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
We can’t do better unless… We can do better with more information For example, if the list is sorted, then we can use that information somehow How? We can play a High-Low game 6
Binary search Repeatedly divide the search space in half We’re looking for 37, let’s say 54 23 31 Check the middle (Too high) Check the middle (Too low) Check the middle (Too low) Check the middle (Found it!) 37 7

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
So, is that faster than linear search? How long can it take? What if you never find what you’re looking for? Well, then, you’ve narrowed it down to a single spot in the array that doesn’t have what you want And what’s the maximum amount of time that could have taken? 8
Running time for binary search We cut the search space in half every time At worst, we keep cutting n in half until we get 1 The running time is O (log n ) For 64 items log n = 6, for 128 items log n = 7, for 256 items log n = 8, for 512 items log n = 9, ….

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 35

week13 - Week 13 Searching and Sorting CS 177 1 Searching...

This preview shows document pages 1 - 10. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online