This program also calculates the time taken by the insertion sort function to run using time() functions. In this program the user generates random numbers using the rand() function in an array and then applies insertion sort to it. Large input is taken in order to get some value of the time taken by the sorting function to perform the sorting, if the input was short the time would have been approximately zero.
#include<stdio.h>
#include<time.h>
int main()
{
int size=100000;
int arr[size];
time_t ct;
time(&ct);
time_t s=time(NULL);
for(int i=0;i<size;i++)
{
arr[i]=rand()%1000+10;//[10,1000]
arr[i]=rand()%100000;
}
for(int i=0;i<size;i++)
{
printf("Index %d:%d\n",i,arr[i]);
}
insertionSort(arr,size);
time_t e=time(NULL);
printf("-------------------------\n");
printf("time taken:%lf\n",difftime(e,s));
for(int i=0;i<size;i++)
{
printf("Index%d:%d\n",i,arr[i]);
}
}
void insertionSort(int arr[],int n)
{
int i,key,j;
for(i=1;i<n;i++)
{
key =arr[i];
j=i-1;
while(j>=0&&arr[j]>key)
{
arr[j+1]=arr[j];
j=j-1;
}
arr[j+1]=key;
}
}

Leave a comment