{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

12-searching-sorting

# 12-searching-sorting - Searching and Sorting CSE 114...

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

Searching and Sorting CSE 114: Computer Science I 1

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

View Full Document
Searching and Sorting Searching and sorting are among the most common operations performed Ex. databases It’s much easier to search data that has been sorted Ex. searching a telephone directory Compare to a linear search 2
Linear Search Examine each element in turn to see if it’s the one you’re looking for On average, you have to examine half of all elements Works even if the list is unsorted Takes time proportional to O(n) (linear) 3

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

View Full Document
Linear Search Code public boolean search (int [] list, int value) { for (int i = 0; i < list.length; i++) { if (list[i] == value) return true; } return false; } 4
Binary Search Method: choose an element at random (usually the middle) and decide whether to search the left or right half Ex. Searching a dictionary for a word At each decision point, the space to be searched is cut in half Requires sorted data to work properly Very efficient: only needs log(n) comparisons 5

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

View Full Document
Pseudocode If (range contains only one element): Look for desired value Else: 1. Get midpoint of range 2. Determine which half of range contains the value 3. Search that half of the range using binary search 6
Binary Search Example Ex. Find 29 Start: [10, 13, 14, 29, 37] Examine 14: [10, 13] [14] [29, 37] Find 29: [10, 13, 14] [29] [37] 7

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

View Full Document
Binary Search Code // Iterative binary search algorithm // Search list from indices first-last public int binSearch (int [] list, int value) { int first = 0; last = list.length - 1; int position = -1; boolean found = false; 8
while (!found && first <= last)

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 / 32

12-searching-sorting - Searching and Sorting CSE 114...

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

View Full Document
Ask a homework question - tutors are online