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". We’ve seen that Kruskal’s 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. We’ll 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 it’s 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
 Spring '01
 Canny
 Data Structures, Databases, Sort, Insertion Sort

Click to edit the document details