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);
}
}




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

QUESTION:
Write a program to perform Selection Sort for an integer array in Java, BlueJ.

CODE:
import java.io.*;
public class SelectionSort
 {
public static int[] sort(int arr[])
{
   for (int i = 0; i < arr.length - 1; i++)
   {
       int index = i;
       for (int j = i + 1; j < arr.length; j++)
       {
           if (arr[j] < arr[index])
           {
               index = j;
           }
       }
       int smallerNumber = arr[index];  
       arr[index] = arr[i];
       arr[i] = smallerNumber;
   }
   return arr;
}
public static void main()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
   int num;
System.out.println("Enter the number of elements to be sorted: ");
num=Integer.parseInt(br.readLine());
int arr1[]=new int[num];
System.out.println("Enter the array to be sorted: ");
for(int i=0;i<arr1.length;i++)
arr1[i]=Integer.parseInt(br.readLine());
int[] arr2 = sort(arr1);
  System.out.println("\nThe elements of the sorted array: "); 
for(int i:arr2)


{
System.out.print(i+"\t");
}
     }

}