C Program for Insertion Sort | C Programming

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

Insertion Sort

Merge Sort

Bubble Sort

Selection Sort

Quick Sort

C Program For Bubble Sort | C Programming

C Program For Selection Sort | C Programming

C Program For Quick Sort | C Programming

C Program For Merge Sort | C Programming

C Program for Insertion Sort | C Programming


Comments

Popular posts from this blog

C Program for SCAN Disk Scheduling Algorithm | C Programming

C program to Find Cartesian Product of Two Sets | C programming

C Program To Check The String Is Valid Identifier Or Not | C Programming