Insertion Sort Using C

Description

 This program is used to sort elements using Insertion Sort.


#include<stdio.h>
void sort();
main()
{
 int choice;
 do
 {
  printf("\n----MENU----\n1.Enter elements\n2.EXIT\n");
  printf("Enter your choice\n");
  scanf("%d",&choice);
  switch(choice)
  {
   case 1:sort();break;
   case 2:printf("\n----Thank you----\n");break;
   default:printf("\nINVALID INPUT !!!!");
  }
 }while(choice!=2);
}

void sort()
{
 int i,temp,n,pass;
 int a[100];
 printf("Enter no. of elements to be sorted\n");
 scanf("%d",&n);
 printf("\nEnter %d elements\n",n);
 for(i=0;i<n;i++)
 {
  scanf("%d",&a[i]);
 }

 
 for(i=1;i<n;i++)
 {
  pass=i;
  while(pass>0 && a[pass]<a[pass-1])
  {
   temp=a[pass];
   a[pass]=a[pass-1];
   a[pass-1]=temp;
   pass--;
  }
 }printf("\n\nSorted Elements are :\n");
 for(i=0;i<n;i++)
 {
  printf("%d\n",a[i]);
 }
}


OUTPUT

Insertion Sort Output 1 Insertion Sort Output 2

Labels: