Friday 29 August 2014

C Program for Insertion Sorting

 C Source code for implementing Insertion Sort. This program accepts No. of values to be sorted and the actual values to be sorted from user. By using Insertion Sort algorithm it sorts the values and prints the output.

Source Code
 
/*
    Insertion sorting
    --------------
    Input :
        1. No. of values to be sorted i.e. n.
        2. Values to be sorted. i.e. n values.
    Output:
        List of sorted values.
*/

# include <stdio.h>
# include <conio.h>


#include <stdio.h>

int main() {
    int n, list[100], i, j, temp;

    clrscr();
    printf("Enter number of elements (maximum: 100):");
    scanf("%d", &n);

    printf("Enter %d values for sorting:\n", n);

    for (i = 0; i < n; i++) {
        scanf("%d", &list[i]);
    }

    for (i = 1 ; i <= n - 1; i++) {
        j = i;

        while ( j > 0 && list[j] < list[j-1]) {
            temp = list[j];
            list[j] = list[j-1];
            list[j-1] = temp;

            j--;
        }
    }



    printf("\n\nSorted list:\n");

    for (i = 0; i <= n - 1; i++) {
        printf("%d\n", list[i]);
    }

    printf("\nPress any key to continue...");
    getch();
    return 0;
}


Output


No comments:

Post a Comment