Quicksort & Mergesort
Quicksort & Mergesort
Divide: Partition (rearrange) the array A[p…r] into two sub-arrays A[p…q-1] and
A[q+1…r] such that each element of A[p…q-1] is less than or equal to
A[q], which is, in turn, less than or equal to each element of A[q+1…r].
Compute the index q as part of this partitioning procedure.
Conquer: Sort the two sub-arrays A[p…q-1] and A[q+1…r] by recursive calls to
quicksort.
Combine: Because the subarrays are already sorted, no work is needed to combine
them: the entire array A[p…r] is now sorted.
QUICKSORT(A, p, r)
1 if p < r
2 q = PARTITION(A, p, r)
3 QUICKSORT(A, p, q – 1)
4 QUICKSORT(A, q + 1, r)
The key to the algorithm is the PARTITION procedure, which rearranges the
subarray A[p…r] in-place.
PARTITION (A, p, r)
1. While data[to_big_index] <= data[pivot]
to_big_index = to_big_index + 1
2. While data[to_small_index] > data[pivot]
to_small_index = to_small_index - 1
3. If to_big_index < to_small_index
swap data[to_big_index] and data[to_small_index]
4. While to_small_index > to_big_index, go to 1.
5. Swap data[to_small_index] and data[pivot_index]
Performance
1
How it works:
1. Choose a value in the array to be the pivot element.
2. Order the rest of the array so that lower values than the pivot element are on the
left, and higher values are on the right.
3. Swap the pivot element with the first element of the higher values so that the pivot
element lands in between the lower and higher values.
4. Do the same operations (recursively) for the sub-arrays on the left and right side
of the pivot element.
Quicksort implementation in C
#include <stdio.h>
//Prototype decleration
void swap(int*, int*);
void printArray(int[], int);
int partition(int[], int, int);
void quickSort(int[], int, int);
// Driver Code
int main()
{
int arr[] = { 70, 6, 10, 50, 9, 2, 1, 15, 70 };
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
2
{
swap(&arr[i], &arr[k]);
k--;
}
}
swap(&arr[low], &arr[k]);
return k;
}
Time complexity
The time complexity of the Quick Sort algorithm is best and average case O(n*log n),
while the worst case is O(n2), where n represents the number of items being sorted.
3
MERGESORT
MERGESORT (A, p, r)
1 if p < r
2 q = (p + r)/2
3 MERGESORT (A, p, q)
4 MERGESORT (A, q+1, r)
5 MERGE (A, p, q, r)
4
Mergesort implementation in C
5
j = 0;
k = p;
// Divide the array into two subarrays, sort them and merge them
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// m is the point where the array is divided into two subarrays
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
6
Time complexity
The Time Complexity of merge sort for Best case, average case and worst case
is O(n*log n), where n represents the number of items being sorted.