Insertion Sort program in C

Insertion Sort:

Insertion sort is somewhat similar to selection but in insertion sort one element is selected from unsorted array and placed at proper location in sorted array.
Worst case performance:     О(n2) comparisons, swaps
Best case performance:         Ω(n) comparisons, O(1) swaps
Average case performance:  Ðž(n2) comparisons, swaps

 

Insertion Sort in C

Insertion Sort in C

#include <stdio.h>
#include <conio.h>

void main( )
{
int arr[5] = { 25, 17, 31, 13, 2 } ;
int i, j, k, temp ;

clrscr( ) ;

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] ) ;

getch( ) ;
}

Insertion Sort in Java

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *