Sort In-Place a –10 2 7 10 2 –4 –7 –10 1 4 5 already • In order to insert, we swap sorted until the element reaches the correct position
Sort In-Place a –10 2 7 2 10 –4 –7 –10 1 4 5 already • In order to insert, we swap sorted until the element reaches the correct position
Sort In-Place a –10 2 2 7 10 –4 –7 –10 1 4 5 already • In order to insert, we swap sorted until the element reaches the correct position
Sort In-Place a –10 2 2 7 –4 10 –7 –10 1 4 5 already • In order to insert, we swap sorted until the element reaches the correct position
Sort In-Place a –10 2 2 –4 7 10 –7 –10 1 4 5 already • In order to insert, we swap sorted until the element reaches the correct position
Sort In-Place a –10 2 –4 2 7 10 –7 –10 1 4 5 already • In order to insert, we swap sorted until the element reaches the correct position
Sort In-Place a –10 –4 2 2 7 10 –7 –10 1 4 5 already • In order to insert, we swap sorted until the element reaches the correct position
Demo
Insertion Sort void insertion_sort (int a[], int size) { for (int i = 1; i < size; i++) { int j = i; while (j > 0 && a[j - 1] > a[j]) { // Swap a[j] and a[j - 1] int tmp = a[j]; a[j] = a[j - 1]; a[j - 1] = tmp; j--; } } } • How many comparisons does insertion_sort() need?
Complexity Having n elements: • Insertion sort: n 2 comparisons
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 10 –10 7 2 2 –4 –7 –10 1 4 5
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 10 –10 7 2 2 –4 –7 –10 1 4 5
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 10 –10 7 2 2 –4 –7 –10 1 4 5
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 –10 –4 2 2 7 10 –10 –7 1 4 5
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 0 1 2 3 4 5 6 7 8 9 10 –10 –4 2 2 7 10 –10 –7 1 4 5
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 –10 0 1 2 3 4 5 6 7 8 9 10 –4 2 2 7 10 –10 –7 1 4 5
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 –10 –10 0 1 2 3 4 5 6 7 8 9 10 –4 2 2 7 10 –7 1 4 5
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 –10 –10 –7 0 1 2 3 4 5 6 7 8 9 10 –4 2 2 7 10 1 4 5
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 –10 –10 –7 –4 0 1 2 3 4 5 6 7 8 9 10 2 2 7 10 1 4 5
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 –10 –10 –7 –4 1 0 1 2 3 4 5 6 7 8 9 10 2 2 7 10 4 5
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 –10 –10 –7 –4 1 2 0 1 2 3 4 5 6 7 8 9 10 2 7 10 4 5
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 –10 –10 –7 –4 1 2 2 0 1 2 3 4 5 6 7 8 9 10 7 10 4 5
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 –10 –10 –7 –4 1 2 2 4 0 1 2 3 4 5 6 7 8 9 10 7 10 5
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 –10 –10 –7 –4 1 2 2 4 5 0 1 2 3 4 5 6 7 8 9 10 7 10
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 –10 –10 –7 –4 1 2 2 4 5 7 0 1 2 3 4 5 6 7 8 9 10 10
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 –10 –10 –7 –4 1 2 2 4 5 7 10 0 1 2 3 4 5 6 7 8 9 10
Merge Sort 0 1 2 3 4 5 6 7 8 9 10 10 –10 7 2 2 –4 –7 –10 1 4 5
Recommend
More recommend