lecture-8

# Pick middle element of the list 2 if middle element

This preview shows page 1. Sign up to view the full content.

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

Unformatted text preview: uss this more later •  But, sorting has a cost! –  we either have to sort as part of search –  sort after insert or remove –  or somehow split the cost (like in a binary search tree) CPSC 223, 2009 12 6 9/23/10 Binary Search •  Given a sorted list, binary search ﬁnds an element in O (log n) time •  Recursively search for an element: 1.  Pick middle element of the list 2.  If middle element == key, then found match 3.  If middle element > key, search left half of list 4.  If middle element < key, search right half of the list CPSC 223, 2009 13 Binary Search (Review) Is C in the List? Input: A B C D E F G Pick middle: A B C D E F G C < D New input: A B C Pick middle: A B C B < C New input: C Pick middle: C Found It! CPSC 223, 2009 14 7 9/23/10 Average-Case Time Complexity •  Many sorting algorithms have O(n2) worst-case and O(nlog n) or O(n) best-case costs –  worst-case is the most “pessimistic” view –  … the algorithm on any problem won’t be slower •  Average-case –  An algorithm is O(f(n)) if the average amount of time it requires to solve a problem of size n is no more than k*f (n) for n > n0 –  Often hard to determine … e.g., what’s the average case? CPSC 223, 2009 15 Three Sorting Algorithms: Selection, Bubble, and Insertion Sort CPSC 223  ­ ­ Fall 2010 16 8 9/23/10 Selection Sort The basic idea –  Select (i.e., “ﬁnd”) the largest item –  Swap it with the last item in the list –  Repeat with items 0 to n – 2 –  Stop when only one item left Pass 1 IniRal list: 29 10 14 13 (n=4) 13 10 14 29 Pass 2 Pass 3 13 10 14 29 13 10 14 29 13 10 14 29 10 13 14 29 CPSC 223, 2009 17 Selection Sort (based on textbook) void selectionSort(Entry theArray, int n) { for(int i = n - 1; i >= 1; i--) { // passes 1..n-1 int index = 0; for(int j = 1; j < i + 1; j++) { // passes 1..i if(...
View Full Document

## This document was uploaded on 03/18/2014 for the course CPSC 223 at Gonzaga.

Ask a homework question - tutors are online