{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

L6_-_Sorting_(4_on_1)

# L6_-_Sorting_(4_on_1) - Lecture Outline Iterative sort...

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

Sorting Bring order to the world 2 --- 74 [CS1102C AY0708S2 Lecture 6] Lecture Outline Iterative sort algorithms (comparison based) Selection Sort Bubble Sort Insertion Sort Recursive sort algorithms (comparison based) Merge Sort Quick Sort Radix sort (non-comparison based) Properties of Sorting In-place sort, stable sort Comparison of sort algorithms Note : we only consider sorting data in ascending order 3 --- 74 [CS1102C AY0708S2 Lecture 6] Why study sorting When an input is sorted, many problems becomes easy (eg. searching, min, max, k th smallest , ...). Sorting has a variety of interesting algorithmic solutions that embody many ideas: Iterative Recursive Divide-and-Conquer Best/Worst/Average-case bounds Randomized Algorithms 4 --- 74 [CS1102C AY0708S2 Lecture 6] Sorting Applications Uniqueness testing Deleting duplicates Prioritizing events Frequency counting Reconstructing the original order Set intersection/union Finding a target pair x , y such that x+y = z Efficient searching

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

View Full Document
Selection Sort 6 --- 74 [CS1102C AY0708S2 Lecture 6] Selection Sort : Idea Given an array of N items: 1. Find the largest item M , in the range of [0…N-1] 2. Swap M with the (N-1) th item 3. Go to step 1, reduce N by 1 7 --- 74 [CS1102C AY0708S2 Lecture 6] Selection Sort : Illustration 13 37 14 10 29 37 13 14 10 29 37 29 14 10 13 37 29 14 10 13 37 29 14 13 10 x x x Unsorted items Largest item for current iteration Sorted items 8 --- 74 [CS1102C AY0708S2 Lecture 6] Selection Sort : Implementation void selectionSort(int a[], int N) { for (int i = N-1; i>=1; --i) { int maxIdx = i; for (int j=0; j<i; ++j) { if (a[j] >= a[maxIdx]) maxIdx = j; } int temp = a[maxIdx] ; a[maxIdx] = a[i] ; a[i] = temp ; } } Step 1. Searching for Maximum element Step 2. Swap maximum element with the last item 13 37 14 10 29 Trace the execution here