{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

13 Searching

# 13 Searching - 1 SORTING AND ASYMPTOTIC COMPLEXITY Lecture...

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
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 9/30/2010 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[k–1]; k––) a[k] = a[k–1]; ¡ Many people sort cards this way ¡ Invariant: everything to left of i is already sorted ¡ Works especially well when input is nearly 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 a[k] = temp; } SelectionSort 3 ¡ To sort an array of size n: ¡ Examine a[0] to a[n–1] ; find the smallest one and swap it with a[0] This is the other common way for people to sort cards Runtime ¡ 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] ¢ Worst-case O(n 2 ) ¢ Best-case O(n 2 ) ¢ Expected-case 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 divide-and-conquer ¡ Caveat: It won’t help unless the partitioning and assembly processes are inexpensive ¡ Can we apply this approach to sorting? MergeSort 5 ¡ 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 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 (...
View Full Document

{[ snackBarMessage ]}

### Page1 / 4

13 Searching - 1 SORTING AND ASYMPTOTIC COMPLEXITY Lecture...

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

View Full Document
Ask a homework question - tutors are online