{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

11-Sorting

# 11-Sorting - InsertionSort CS/ENGRD 2110 Object-Oriented...

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

3/1/2011 1 CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2010 Thorsten Joachims Lecture 11: Sorting InsertionSort Many people sort cards this way Invariant: everything to left of i is already sorted Worst-case is O(n 2 ) Consider reverse-sorted input Best-case is O(n) Consider sorted input Expected case is O(n 2 ) Expected number of inversions is n(n 1)/4 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[k 1]; k –– ) a[k] = a[k 1]; a[k] = temp; } SelectionSort To sort an array of size n: Examine a[0] to a[n 1]; find the smallest one and swap it with a[0] Examine a[1] to a[n 1]; find the smallest one and swap it with a[1] In general, in step i, examine a[i] to a[n 1]; find the smallest one and swap it with a[i] This is the other common way for people to sort cards Runtime Worst-case O(n 2 ) Best-case O(n 2 ) Expected-case O(n 2 ) 3 Divide & Conquer? It often pays to Break the problem into smaller subproblems, Solve the subproblems separately, and then Assemble a final solution This technique is called divide-and-conquer Caveat: It won’t help unless the partitioning and assembly processes are inexpensive Can we apply this approach to sorting? 4 MergeSort Quintessential divide-and-conquer 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 5 Merging Sorted Arrays A and B 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 0 (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 or A, respectively) into C 6

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

View Full Document
3/1/2011 2 Merging Sorted Arrays 7 1 3 4 4 6 7 C = merged array B A
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 4

11-Sorting - InsertionSort CS/ENGRD 2110 Object-Oriented...

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

View Full Document
Ask a homework question - tutors are online