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: 10/8/2009 1 SORTING AND ASYMPTOTIC COMPLEXITY Lecture 13 CS2110 Fall 2009 InsertionSort 2 //sort a, an array of int for (int i = 1; i < a.length; i++) { int temp = a[i]; int k; for (k = i; 0 < k && temp < a[k1]; k) a[k] = a[k1]; Many people sort cards this way Invariant: everything to left of i is already sorted Works especially well when input is nearly sorted y Worstcase is O(n 2 ) Consider reversesorted input y Bestcase is O(n) Consider sorted input y Expected case is O(n 2 ) Expected number of inversions is n(n1)/4 a[k] = temp; } SelectionSort 3 To sort an array of size n: Examine a[0] to a[n1] ; find the smallest one and swap it with a[0] Examine a[1] to a[n1] ; y This is the other common way for people to sort cards y Runtime find the smallest one and swap it with a[1] In general, in step i, examine a[i] to a[n1] ; find the smallest one and swap it with a[i] Worstcase O(n 2 ) Bestcase O(n 2 ) Expectedcase O(n 2 ) Divide & Conquer? 4 It often pays to Break the problem into smaller subproblems, Solve the subproblems separately, and then Assemble a final solution Assemble a final solution This technique is called divideandconquer Caveat: It wont help unless the partitioning and assembly processes are inexpensive Can we apply this approach to sorting? MergeSort 5 Quintessential divideandconquer algorithm Divide array into equal parts, sort each part, then merge Questions: Q1: How do we divide array into two equal parts? A1: Find middle index: a.length/2 Q2: How do we sort the parts? A2: call MergeSort recursively! Q3: How do we merge the sorted subarrays? A3: We have to write some (easy) code Merging Sorted Arrays A and B 6 Create an array C of size = size of A + size of B Keep three indices: i into A j into B k into C Initialize all three indices to (start of each array) Compare element A[i] with B[j] , and move the smaller element into C[k] Increment i or j , whichever one we took, and k When either A or B becomes empty, copy remaining elements from the other array ( B...
View
Full
Document
This note was uploaded on 03/08/2010 for the course CS 2110 taught by Professor Francis during the Spring '07 term at Cornell University (Engineering School).
 Spring '07
 FRANCIS
 Data Structures, Sort, Selection Sort

Click to edit the document details