Mergesort is a divide and conquer algorithm that does exactly that. It splits the list in half
Mergesorts the two halves Then merges the two sorted halves together Mergesort can be implemented recursively
16. Mergesort Split the list in half. Mergesort the left half. Split the list in half. Mergesort the left half. Split the list in half. Mergesort the left half. 10 Mergesort the right. 4 http://ecomputernotes.com 8 12 11 2 7 5 4 10 8 12 4 10 4 10
17. Mergesort 8 12 4 10 Mergesort the right half. Merge the two halves. 12 8 http://ecomputernotes.com 8 12 11 2 7 5 4 10 4 10 10 4 8 12 Merge the two halves . 8 8 12
18. Mergesort 8 12 4 10 Merge the two halves. Mergesort the right half. Merge the two halves. http://ecomputernotes.com 8 12 11 2 7 5 4 10 4 10 10 4 8 12 10 12 8 4 10 4 8 12
39. Merge Sort and Linked Lists http://ecomputernotes.com Sort Sort Merge
40.
41.
42.
43. Quicksort First the list is partitioned around a pivot value. Pivot can be chosen from the beginning, end or middle of list): 8 3 2 11 7 5 12 4 5 http://ecomputernotes.com 4 10 5 pivot value
44. Quicksort The pivot is swapped to the last position and the remaining elements are compared starting at the ends. 8 3 2 11 7 5 12 4 5 5 pivot value http://ecomputernotes.com 4 10 low high
45. Quicksort Then the low index moves right until it is at an element that is larger than the pivot value (i.e., it is on the wrong side) 8 6 2 11 7 5 10 12 4 6 5 pivot value 3 12 http://ecomputernotes.com low high
46. Quicksort Then the high index moves left until it is at an element that is smaller than the pivot value (i.e., it is on the wrong side) 8 6 2 11 7 5 12 4 6 5 pivot value 3 2 http://ecomputernotes.com 4 10 low high
47. Quicksort Then the two values are swapped and the index values are updated: 8 6 2 11 7 5 12 4 6 5 pivot value 3 2 12 http://ecomputernotes.com 4 10 low high
48. Quicksort This continues until the two index values pass each other: 8 6 12 11 7 5 4 2 4 6 5 pivot value 3 10 3 10 http://ecomputernotes.com low high
49. Quicksort This continues until the two index values pass each other: 8 6 12 11 7 5 4 2 4 6 5 pivot value 10 3 http://ecomputernotes.com low high
50. Quicksort Then the pivot value is swapped into position: 8 6 12 11 7 5 4 2 4 6 10 3 8 5 http://ecomputernotes.com low high
51. Quicksort Recursively quicksort the two parts: 5 6 12 11 7 8 4 2 4 6 10 3 5 http://ecomputernotes.com Quicksort the left part Quicksort the right part
52. Quicksort void quickSort(int array[], int size) { int index; if (size > 1) { index = partition(array, size); quickSort(array, index); quickSort(array+index+1, size - index-1); } } http://ecomputernotes.com
53. int partition(int array[], int size) { int k; int mid = size/2; int index = 0; swap(array, array+mid); for (k = 1; k < size; k++){ if (array[k] < array[0]){ index++; swap(array+k, array+index); } } swap(array, array+index); return index; } Quicksort