insertion sort in java

import java.io.DataInputStream;
class InsertionSort
{
public static void main(String args[ ])
{
int i,n=0;
int x[]=new int[25];
DataInputStream in = new DataInputStream(System.in);
try
{
System.out.print("Enter how many numbers to be sorted : ");
n = Integer.parseInt(in.readLine());
System.out.println("Enter "+n+" numbers in any order....");
for(i=0;i<n;i++)
{
System.out.print("\t\tElement x["+(i+1)+"]=");
x[i] = Integer.parseInt(in.readLine());
}
}
catch(Exception e)
{
System.out.println("I/O Error");
}
insertion(x,n);
System.out.println("\nSorted Elements are :");
for(i=0;i<n;i++)
System.out.println("\t\tElement x["+(i+1)+"]="+x[i]);
}
static void insertion(int x[],int n)
{
int i,k,y;
for(k=1;k<n;k++)
{
y=x[k];
for(i=k-1;i>=0&&y<x[i];i--)
x[i+1]=x[i];
x[i+1]=y;
}
}
}

/* insertion sort in java OUTPUT
Enter how many numbers to be sorted : 5
Enter 5 numbers in any order....
Element x[1]=4
Element x[2]=2
Element x[3]=3
Element x[4]=7
Element x[5]=8

Sorted Elements are :
Element x[1]=2
Element x[2]=3
Element x[3]=4
Element x[4]=7
Element x[5]=8 */

Facing difficulties in understanding the program ?

Ask Your Queries in Comment Box

You may also like...

Leave a Reply

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