0% found this document useful (0 votes)
8 views2 pages

PGM 2 Merge Sort

The document contains a C program that implements the merge sort algorithm to sort an array of random integers. It measures the time taken to sort the array and outputs the sorted array and the time taken to a file named 'time1.txt'. The program prompts the user for the number of elements to sort and generates random integers for the array.

Uploaded by

Lucky Sinha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

PGM 2 Merge Sort

The document contains a C program that implements the merge sort algorithm to sort an array of random integers. It measures the time taken to sort the array and outputs the sorted array and the time taken to a file named 'time1.txt'. The program prompts the user for the number of elements to sort and generates random integers for the array.

Uploaded by

Lucky Sinha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdlib.h>
#include <time.h>

void merge(int arr[], int l, int m, int r)


{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

int L[n1], R[n2];

for (i = 0; i < n1; i++)


L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
} else
{
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1)


{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(int arr[], int l, int r)


{
if (l < r)
{
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
int main()
{
int n, i, a[100000];
clock_t start,end;
double cpu_time_used;
FILE *fp = fopen("time1.txt","w");
if (fp == NULL)
{
printf("Error opening file.\n");
return 1;
}
printf("enter n:\n");
scanf("%d",&n);
fprintf(fp,"n=%d\n",n);
for (i = 0; i < n; i++)
{
a[i] = rand()%10000;
printf("%d\n",a[i]);
}
start = clock();
printf("start time is %ld\n",start);
mergeSort(a,0,n-1);
printf("time in ms\n");
for (i = 0; i < n; i++)
{
printf("%d\n",a[i]);
fprintf(fp,"%d\n",a[i]);
}
end = clock();
printf("end time is %ld\n",end);
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC * 1000;
printf("time taken to sort elements : %f miliseconds\n",cpu_time_used);
fprintf(fp,"Time taken to sort elements: %f milliseconds\n",cpu_time_used);
fclose(fp);
return 0;

You might also like