C code for Insertion Sort

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

}


Related Posts

  • Share/Bookmark
You can leave a response, or trackback from your own site.

5 Responses to “C code for Insertion Sort”

  1. Mark4 says:

    Thank You^6

  2. mahesh says:

    this is good.thankz

  3. Kiran says:

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

  4. nbpro says:

    thanks..nice programm

Leave a Reply

| Shop Free Cellular Phones at Bestincellphones.com. | Thanks to Best CD Rates, iCellPhoneDeals.com Offers Best Cell Phone Deals. and Incinerador De Grasa