C Program For Insertion Sort Using time.h Function and Generating Random Number

#include <math.h> 
#include<time.h>
#include<stdlib.h>
#include <stdio.h>
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;
     }
}
void printArray(int arr[], int n)
{
    int i;
    for (i = 0; i < n; i++)
         printf("%d  ", arr[i]);
     printf("\n");
}
int main()
{
     int arr[100],n,i;
     time_t t;
     printf("Enter the max number \n");
     scanf("%d",&n);
     srand((unsigned) time(&t));
     for(i=0;i<n;i++)
     {
         arr[i]=rand()%100;
     }
     printf("\nThe random numbers are:\n");
     for(i=0;i<n;i++)
     {
         printf("%d  ",arr[i]);
     }
     insertionSort(arr, n);
    printf("\n\nTime taken to complete the insertion sort %u\n",clock()/CLOCKS_PER_SEC);
    printf("\nThe sorted list is:\n");
    printArray(arr, n);
     return 0;
}

Related Posts

Quick Sort

Bubble Sort

Merge Sort

Selection Sort

C Program For Selection Sort | C Programming

C Program For Quick Sort | C Programming

C Program For Merge Sort | C Programming

C Program For Bubble Sort | C Programming


Share To:

Arogya Thapa Magar

Post A Comment:

0 comments so far,add yours