C Program to Sort the Array Using Insertion Sort Technique


 

// Program by Akash Tripathi (@proakash256)
 
// In Insertion Sort , the Array is virtually
// split into a Sorted part and an Unsorted part
// from which the elements are picked and placed
// at the correct position in the Sorted part.

// Algorithm :
// 1. Iterate from Array[1] to Array[N].
// 2. Compare the Current Element to its Predecessor.
// 3. If the Current Element is smaller
// than its Predecessor,
//    Compare it to the Element before.
// Move the greater elements
//    one position up to make space
// for Swapped Elements.

#include <stdio.h>
int main()
{
    int n , key , i , j;
    printf("Enter the number of elements
            you want to enter in the array : ");
    scanf("%d" , &n);
    int ar[n];
    printf("\nEnter the elements :\n");
    for(int i = 0i < ni = i + 1)
        scanf("%d" , &ar[i]);
    printf("\nEnter 1 to Sort in Ascending Order\n");
    printf("Enter 2 to Sort in Descending Order\n");
    printf("Enter your Choice : ");
    char c;
    scanf(" %c" , &c);
    if(c == '1')
    {
        for(i = 1i < ni = i + 1)
        {
            key = ar[i];
            j = i - 1;
            while(j >= 0 && ar[j] > key)
            {
                ar[j + 1] = ar[j];
                j = j - 1;
            }
            ar[j + 1] = key;
        }
    }
    else if(c == '2')
    {
        for(i = 1i < ni = i + 1)
        {
            key = ar[i];
            j = i - 1;
            while(j >= 0 && ar[j] < key)
            {
                ar[j + 1] = ar[j];
                j = j - 1;
            }
            ar[j + 1] = key;
        }
       
    }
    else
        printf("Sorry Wrong Choice...\n");
    printf("\nThe Sorted array is :\n");
    for(int i = 0i < ni = i + 1)
        printf("%d\n" , ar[i]);
    return 0;
}

Comments