Wednesday, July 15, 2015

WAP to perform Insertion Sort for an integer array in Java, BlueJ.

QUESTION:
Wrtie a program to perform insertion sort for an integer array in Java, BlueJ.

CODE:
import java.io.*;
class InsertionSort
 {

public static void main()throws IOException 
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int num;
System.out.print("Enter the number of elements to be sorted: ");
num=Integer.parseInt(br.readLine());
int input[]=new int[num];
System.out.println("Enter the elements to be sorted: ");
for(int i=0;i<num;i++)
{
input[i]=Integer.parseInt(br.readLine());
        }
sort(input);
}
public static void display(int[] input) 
{
System.out.println("\nThe elements of the sorted array: ");
for (int i = 0; i < input.length; i++) 
{
System.out.print(input[i]+"\t");
}
System.out.println("\n");
}
public static void sort(int array[]) 
{
int n = array.length;
for (int j = 1; j < n; j++) 
{
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) 
{
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
display(array);
}
}




No comments:

Post a Comment