07-sorting

# 07-sorting - SEARCHING AND SORTING ISE 208(Intermediate...

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

SEARCHING AND SORTING ISE 208 (Intermediate Programming) SUNY at Stony Brook 1

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

View Full Document
SEARCHING AND SORTING Searching and sorting are fundamental operations in computer programming Searching and sorting go hand in hand Sorted data is much easier to 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 the data set to Fnd what you’re looking for Works even if the list is unsorted Takes time proportional to O(n) (linear) The time needed increases at the same rate as the size of the data set increases 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; // we found our value } return false; } 4
BINARY SEARCH Method: choose an element at random (usually the middle) and decide whether to search the left or right half At each decision point, the space to be searched is cut in half Requires sorted data to work properly Very efFcient: only needs log 2 (n) comparisons Twice as much data only needs one more step 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 the range is likely to contain the desired value 3. Repeat the binary search on just that half of the range 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 Frst-last public int binSearch (int [] list, int value) { int Frst = 0; last = list.length - 1; int position = -1; boolean found = false; 8
{ int middle = (Frst + last) / 2; if (list[middle] == value) { found = true; position = middle; } 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 / 29

07-sorting - SEARCHING AND SORTING ISE 208(Intermediate...

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

View Full Document
Ask a homework question - tutors are online