Writing programs for sorting of a given set of numbers is one of the common programming tasks. Various types of sorting techniques like selection sort, inserting sort and quick sort are quite popular. Here C code for Insertion sort is being presented. The program is quite simple. Here, in each iteration, the elements are placed in their correct position. The algorithm has the complexity of O(n²)
#include "stdio.h"
void main( )
{
int arr[5] = { 25, 17, 31, 13, 2 } ;
int i, j, k, temp ;
printf ( "Insertion sort.\n" ) ;
printf ( "\nArray before sorting:\n") ;
for ( i = 0 ; i <= 4 ; i++ )
printf ( "%d\t", arr[i] ) ;
for ( i = 1 ; i <= 4 ; i++ )
{
for ( j = 0 ; j < i ; j++ )
{
if ( arr[j] > arr[i] )
{
temp = arr[j] ;
arr[j] = arr[i] ;
for ( k = i ; k > j ; k-- )
arr[k] = arr[k - 1] ;
arr[k + 1] = temp ;
}
}
}
printf ( "\n\nArray after sorting:\n") ;
for ( i = 0 ; i <= 4 ; i++ )
printf ( "%d\t", arr[i] ) ;
}

Posted in
Tags: 

Thank You^6
this is good.thankz
Hey Bro , why are you using 3 loops it looks a bit complicated.
Try this one
http://electrofriends.com/source-codes/software-programs/c/sorting-programs/program-to-sort-the-numbers-using-insertion-sort/
public class InsertionSort {
public static void main(String args[]) {
int arr[] = { 3,5, 4, 0, 2, 1 };
for (int i = 1; i = 0 && arr[j] > temp) {
arr[j + 1] = arr[j];
j–;
}
arr[j+1] = temp;
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
thanks..nice programm