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]); } }
Pingback: Java program for Insertion Sort | Letusprogram