/* C program to count comparisons in different
cases of Merge Sort */
#include<stdlib.h>
#include<stdio.h>
// Total number of comparisons
int count = 0;
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// If already sorted, return
if (arr[m] <= arr[m+1])
{
count += 1;
return;
}
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
count+=2;
if (L[i] <= R[j])
{
count+=1;
arr[k] = L[i];
i++;
}
else
{
count+=1;
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
count+=1;
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
count+=1;
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
count+=1;
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
/* Driver program to test above functions */
int main()
{
// produces worst case of merge sort
int arrw[] = {1, 9, 5, 13, 3, 11, 7, 15,
2, 10, 6, 14, 4, 12, 8, 16};
int nw = sizeof(arrw)/sizeof(arrw[0]);
printf("Given array is \n");
printArray(arrw, nw);
mergeSort(arrw, 0, nw - 1);
printf("Sorted array is \n");
printArray(arrw, nw);
printf("Total no. of comparisons in this case"
" are %d\n", count);
// Resetting global variable count to 0
count = 0;
// produces best case of merge sort
int arrb[] = {1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16};
int nb = sizeof(arrb)/sizeof(arrb[0]);
printf("\nGiven array is \n");
printArray(arrb, nb);
mergeSort(arrb, 0, nb - 1);
printf("Sorted array is \n");
printArray(arrb, nb);
printf("Total no. of comparisons in this case"
" are %d\n", count);
return 0;
}