This preview shows pages 1–2. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: 04/08/09 03:19:43 1 30 CS 61B: Lecture 30 Wednesday, April 8, 2009 SORTING ======= The need to sort numbers, strings, and other records arises frequently. The entries in any modern phone book were sorted by a computer. Databases have features that sort the records returned by a query, ordered according to any field the user desires. Google sorts your query results by their "relevance". Weve seen that Kruskals algorithm uses sorting. So do hundreds of other algorithms. Sorting is perhaps the simplest fundamental problem that offers a huge variety of algorithms, each with its own inherent advantages and disadvantages. Well study and compare eight sorting algorithms. Insertion Sort Insertion sort is very simple and runs in O(n^2) time. We employ a list S, and maintain the invariant that S is sorted. Start with an empty list S and the unsorted list I of n input items. for (each item x in I) { insert x into the list S, positioned so that S remains in sorted order. } S may be an array or a linked list. If S is a linked list, then it takes Theta(n) worstcase time to find the right position to insert each item. If S is an array, we can find the right position in O(log n) time by binary search, but it takes Theta(n) worstcase time to shift the larger items over to make room for the new item. In either case, insertion sort runs in Theta(n^2) worstcase timebut for a different reason in each case. If S is an array, one of the nice things about insertion sort is that its an inplace sort. An _inplace_sort_ keeps the sorted items in the same array that initially held the input items. Besides the input array, it uses only O(1) or perhaps O(log n) additional memory. To do an inplace insertion sort, we partition the array into two pieces: the left portion (initially empty) holds S, and the right portion holds I. With each iteration, the dividing line between S and I moves one step to the right....
View
Full
Document
This note was uploaded on 02/21/2010 for the course CS 61B taught by Professor Canny during the Spring '01 term at University of California, Berkeley.
 Spring '01
 Canny
 Data Structures, Databases, Sort

Click to edit the document details