Showing posts with label insertion sort. Show all posts
Showing posts with label insertion sort. Show all posts

Saturday, 21 September 2013

Showing posts with label insertion sort. Show all posts
Showing posts with label insertion sort. Show all posts

Saturday, 21 September 2013

Program in C for Insertion Sort


C program for Insertion sort:

Insertion sorting algorithm sorts one element at a time. It begins by sorting the first 2 elements in order. In the next step, it takes the third element and compares it against the first two sorted elements. Exchanges are made if necessary and the 3 elements will be sorted with respect to each other. As next step, it takes the fourth element and it compares against the first 3 sorted elements. The process repeats until the whole array of elements are sorted.

#include <stdio.h>
#include <stdlib.h>
int main(){
    int a[10];
     int i,size,j,temp;
    printf("enter sizeelements");
    scanf("%d",&size);
  
    for(i=0;i<size;i++){
    scanf("%d ",&a[i]);
    }
  
  
    for(i=0;i<size;i++){
        for(j=0;j<i;j++){
            
            if(a[j+1]<a[j]){
                temp=a[j+1];
                a[j+1]=a[j];
                a[j]=temp;
                
            }
            
        }
    }
    printf("After sort ");
    for(i=0;i<size;i++){
    printf("%d ",a[i]);
    }
 return 0;
 }

Executing the program....
$demo
enter sizeelementsAfter sort 2 5 45 67 77