Chapter 12
Chapter 12
Chapter 12
Chapter 12
Chapter Contents
Merge Sort
• Merging Arrays
• Recursive Merge Sort
• The Efficiency of Merge Sort
• Iterative Merge Sort
• Merge Sort in the Java Class Library
Quick Sort
• The Efficiency of Quick Sort
• Creating the Partition
• Java Code for Quick Sort
• Quick Sort in the Java Class Library
Radix Sort
• Pseudocode for Radix Sort
Comparing the Algorithms
2
Merge Sort
Divide an array into halves
• Sort the two halves
• Merge them into one sorted array
3
Merge Sort
Fig. 12-1
Merging two
sorted arrays
into one sorted
array.
4
Merge Sort
5
Merge Sort
Algorithm mergeSort(a, first, last)
// Sorts the array elements a[first] through a[last] recursively.
if (first < last)
{
mid = (first + last)/2
mergeSort(a, first, mid)
mergeSort(a, mid+1, last)
Merge the sorted halves a[first..mid] and a[mid+1..last]
}
6
Merge Sort
10
Quick Sort
11
Quick Sort
12
Quick Sort
Fig. 12-7 (a) The array with its first, middle, and
last elements sorted; (b) the array after
positioning the pivot and just before partitioning.
16
Quick Sort
Quick sort rearranges the elements in an
array during partitioning process
After each step in the process
• One element (the pivot) is placed in its correct
sorted position
The elements in each of the two sub arrays
• Remain in their respective subarrays
21
Comparing the Algorithms
23