Insertion Sort Algorithm | C Programming | Factsprime – DSA

Write a Modular C Programming code for ‎Insertion Sort Algorithm DSA

insertion-sort

Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.

Refer : C Programming HackerRank all solutions for Loops | Arrays | strings | Data Structures | Linked lists | Stacks | Queues | Binary Trees

 

CODE:

#include<stdio.h>

insertion(int a[1000],int n)
{
    int key;

 for(int i=0;i<n;i++)
  { 
   int j=i-1; 
   key=a[i]; 
   while(j>=0&&a[j]>key){
        a[j+1]=a[j];
        j--;
    }
    a[j+1]=key;
 }
    printf("\n\nSorted array is: ");
    print(a,n);

}
print(int a[1000],int n)
{
    for(int i=0;i<n;i++){
        printf("%d ",a[i]);
    }
}
main()
{
    int n,a[1000];

    printf("Enter the size: ");
    scanf("%d",&n);

    printf("Enter Numbers: ");

    for(int i=0;i<n;i++){
        a[i]=(rand()%200);

    }

    print(a,n);
    insertion(a,n);

}


OUTPUT

Enter the size: 16
Enter Numbers: 41 67 134 100 169 124 78 158 162 64 105 145 81 27 161 91

Sorted array is: 27 41 64 67 78 81 91 100 105 124 134 145 158 161 162 169
Process returned 0 (0x0)   execution time : 4.057 s
Press any key to continue.

Please find some more codes of Loops, Condition Statements, 1D Arrays, 2D Arrays, Strings, Pointers, Data Structures, Files, Linked lists, Stacks, Queues, Binary Trees, MISC, Solved model question papers & Hacker Rank all solutions on the below page:

Top 100+ C Programming codes – KLE Technological University

Leave a Comment

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

Welcome to FactsPrime

Sorry, We have detected that you have activated Ad-Blocker. Please Consider supporting us by disabling your Ad Blocker, It helps us in maintaining this website. To View the content, Please disable adblocker and refresh the page.

Thank You !!!