Insertion Sort: This sorting algorithm is same as sorting a deck of cards. We pickup a card in one hand and then compare each subsequent card with it and insert the card into the sorted deck. That is we pick one card at a time and insert it into sorted deck at the right place.
Program:
public class InsertionSort {
public static void main(String[] args) {
System.out.println("Enter the number of elements : ");
Scanner obj=new Scanner(System.in);
int n=obj.nextInt();
double arr[]=new double[n];
System.out.println("Enter "+n+" elements : ");
for(int i=0;i<n;i++){
arr[i]=obj.nextDouble();
}
int i;double key;
for(int j=1;j<n;j++){
key=arr[j];
i=j-1;
while(i>=0&&arr[i]>key){
arr[i+1]=arr[i];
arr[i]=key;
i--;
}
}
for(i=0;i<n;i++){
System.out.println(arr[i]);
}
}
}
No comments:
Post a Comment