Lecture08

# Lecture08 - Lecture 8 Sorting CS2134 Insertion Sort 20 37...

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

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

View Full Document

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

View Full Document

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

View Full Document

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: Lecture 8: Sorting CS2134 Insertion Sort 20 37 43 25 4 72 15 a[0..p-1] sorted rest of array Insert element a[p] in a[0..p-1], sliding larger elements over to make room: 20 25 37 43 4 72 15 a[0..p] sorted CS2134 rest of array // Simple insertion sort. template void insertionSort( vector & a ) { int j; for( int p = 1; p < a.size( ); p++ ) { Comparable tmp = a[ p ]; for( j = p; j > 0 && tmp < a[ j - 1 ]; j-- ) a[ j ] = a[ j - 1 ]; a[ j ] = tmp; } } Note nested for loop CS2134 Analysis of Insertion Sort Worst case: 1+ 2 + ... + n = O(n2) Average case: similar ... O(n2) Best case (Array is already sorted) inner loop iterates 0 times for each p O(n) [!] Interesting special case: array is almost sorted ... similar to best case CS2134 Analysis of Insertion Sort Worst case: 1+ 2 + ... + n = O(n2) Average case: similar ... O(n2) Best case (Array is already sorted) inner loop iterates 0 times for each p O(n) [!] Interesting special case: array is almost sorted ... similar to best case CS2134 Merge Sort 43 37 20 25 4 72 15 19 DIVIDE IN HALF 43 37 20 25 4 72 15 19 SORT EACH HALF 20 4 25 15 37 19 43 20 4 MERGE 25 CS2134 15 37 19 43 72 72 Merge Given two sorted sub arrays, combine them into a single sorted array Use auxilliary array successively compare smallest elements when one runs out, copy the rest of the other code for merge scans each element once: O(n) time also uses O(n) space CS2134 Merge Sort Divide array into two (almost) equal pieces Conquer: sort each half recursively merge the sorted arrays code Analysis: log n stages, each of which is linear O(n log n) CS2134 ...
View Full Document

{[ snackBarMessage ]}

### Page1 / 8

Lecture08 - Lecture 8 Sorting CS2134 Insertion Sort 20 37...

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

View Full Document
Ask a homework question - tutors are online