Insertion Sort in C

What is Insertion Sort? As said Before, Insertion sort is better technique when compared to Bubble sort. But it cant handle data of large size. So we need to go for selection sort and heap sort techniques. Insertion Sort is done by comparing key element with the predecessor and sort them according to the result. If the element is larger than key element, then swap both the elements and again compare key element with the predecessor. Insertion sort in Java

#include <stdio.h>
#include <conio.h>
void sort(int);

void main(){
    int size;

    printf("\n Enter size of the array: "); //Request for size of array
    scanf("%d",&size);
    sort(size); //Invoking sorting function with size as parameter

    getch();
};

void sort(int size){
    int data[size],i,j,order,temp;

    for(i=0;i< size; i++){
        printf("\n Enter data into the array: "); //Enter the data into the array
        scanf("%d",&data[i]);
    }

    for(i=1;i<size;i++){
        	j=i;
        	while(j>0 && data[j-1] > data[j]){
        		temp = data[j-1];
        		data[j-1] = data[j];
        		data[j] = temp;
        		j--;
        	}
    }

    printf("\n Sorted data is:\n"); //Display of final sorted data
        for(i=0;i<size;i++){
            printf("\t%d",data[i]);
        }
}

Output:
insertion output

Download the Source Code

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in C and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

1 Response to Insertion Sort in C

  1. Pingback: Java program for Insertion Sort | Letusprogram

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s