C Program For Merge Sort by Generating Random Numbers and Using time.h Function

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

void mergesort(int a[],int i,int j);

void merge(int a[],int i1,int j1,int i2,int j2);

int main()

{

int a[30],n,i;
 time_t t;
 printf("Enter the max number \n");
 scanf("%d",&n);
 srand((unsigned) time(&t));
 for(i=0;i<n;i++)
 {
 a[i]=rand()%100;
 }
 for(i=0;i<n;i++)
 {
 printf("%d\t",a[i]);
 }

mergesort(a,0,n-1);
 
 printf("\n\nTime taken to complete the mergesort %u\n",clock()/CLOCKS_PER_SEC);

printf("\nSorted array is :\n");

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

printf("%d\t",a[i]);

return 0;
}

void mergesort(int a[],int i,int j)

{
 int mid;

if(i<j)

{

mid=(i+j)/2;

mergesort(a,i,mid); //left

mergesort(a,mid+1,j); //right

merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays

}

}

void merge(int a[],int i1,int j1,int i2,int j2)

{

int temp[50]; //array used for merging

int i,j,k;

i=i1; //beginning of the first list

j=i2; //beginning of the second list

k=0;

while(i<=j1 && j<=j2) //while elements in both lists

{

if(a[i]<a[j])

temp[k++]=a[i++];

else

temp[k++]=a[j++];

}

while(i<=j1) //copy remaining elements of the first list

temp[k++]=a[i++];

while(j<=j2) //copy remaining elements of the second list

temp[k++]=a[j++];

//Transfer elements from temp[] back to a[]

for(i=i1,j=0;i<=j2;i++,j++)

a[i]=temp[j];

}

Related Posts

Bubble Sort

Insertion Sort

Merge Sort

Selection Sort

Quick Sort

C Program For Selection Sort | C Programming

C Program For Quick Sort | C Programming

C Program For Bubble Sort | C Programming

C Program for Insertion Sort | C Programming