Recursive Sort
Recursive Sort
Merge Sort
•In plain English: if the size of the array > 1,
split the array into two halves, and recursively
sort both halves; when the sorts return, merge
the two halves
•Pseudocode for function mergesort:
if array size equals 1
return
copy first half into leftArray
copy second half into rightArray
sort (leftArray)
sort (rightArray)
merge leftArray with rightArray
Execution Example
• Partition
7 2 9 4 3 8 6 1 1 2 3 4 6 7 8 9
7 2 9 4 2 4 7 9 3 8 6 1 1 3 8 6
7 2 2 7 9 4 4 9 3 8 3 8 6 1 1 6
7 29 4 2 4 7 9 3 8 6 1 1 3 8 6
7 2 2 7 9 4 4 9 3 8 3 8 6 1 1 6
7 29 4 2 4 7 9 3 8 6 1 1 3 8 6
722 7 9 4 4 9 3 8 3 8 6 1 1 6
7 29 4 2 4 7 9 3 8 6 1 1 3 8 6
722 7 9 4 4 9 3 8 3 8 6 1 1 6
7 29 4 2 4 7 9 3 8 6 1 1 3 8 6
722 7 9 4 4 9 3 8 3 8 6 1 1 6
7 29 4 2 4 7 9 3 8 6 1 1 3 8 6
722 7 9 4 4 9 3 8 3 8 6 1 1 6
7 29 4 2 4 7 9 3 8 6 1 1 3 8 6
722 7 9 4 4 9 3 8 3 8 6 1 1 6
7 29 4 2 4 7 9 3 8 6 1 1 3 8 6
722 7 9 4 4 9 3 8 3 8 6 1 1 6
7 29 4 2 4 7 9 3 8 6 1 1 3 6 8
722 7 9 4 4 9 3 8 3 8 6 1 1 6
7 29 4 2 4 7 9 3 8 6 1 1 3 6 8
722 7 9 4 4 9 3 8 3 8 6 1 1 6
m = ( i + j )/2; main( )
{
mergeSort (A, i, m); int A[100];
int size;
mergeSort (A, m+1, j); /* read array A and its size */
mergeSort(A[ ], 0, size-1);
merge (A, i, m, j); }
}
Merge Method
•Merge algorithm in plain English: while left & right
arrays still have elements, copy the lower element from
either into the merged array; when either left or right
array is exhausted, copy the remainder of the other
array into the merged array
•In pseudocode:
while neither array exhausted
if element of left array < element of right array
copy left element into merged array & increment index
else
copy right element into merged array & increment index
copy balance of unexhausted array into merged
array
Function merge
void merge ( int i1, int j1, int j2 )
{
int i2, k1, k2, k;
int tmpArray[100];
i2 = j1 + 1;
k1 = i1; k2 = i2; k = 0;
45312
Insertion Sort
45312
Insertion Sort
45312
Insertion Sort
45312
4 512
Insertion Sort
45312
4 512
4512
Insertion Sort
45312
4 512
4512
34512
Insertion Sort
45312 34512
4 512
4512
34512
Insertion Sort
45312 34512
4 512 34 52
4512
34512
Insertion Sort
45312 34512
4 512 34 52
4512 3 452
34512
Insertion Sort
45312 34512
4 512 34 52
4512 3 452
34512 3452
Insertion Sort
45312 34512
4 512 34 52
4512 3 452
34512 3452
13452
Insertion Sort
4 512 34 52
4512 3 452
34512 3452
13452
Insertion Sort
4 512 34 52 134 5
4512 3 452
34512 3452
13452
Insertion Sort
4 512 34 52 134 5
4512 3 452 13 45
34512 3452
13452
Insertion Sort
4 512 34 52 134 5
4512 3 452 13 45
13452
Insertion Sort
4 512 34 52 134 5
4512 3 452 13 45
13452 12345
for (i=1; i<n; ++i)
{
/* Consider A[i] */
/* Search for the correct insertion location of A[i] */
t = A[i];
/* Store A[i] in a temporary variable */