Can someone just comment this program out? Please... explain what each line does or atleast for most of the important lines
Can someone just comment this program out? Please... explain what each line does or atleast for most of the important lines
--------------------------------------------
import java.util.*;
import java.io.*;
public class InsertionSort
{
static int shiftcount;
static int gch;
public static void insertionLast(int [] arr, int size)
{
if(gch==2)
{
int L=arr[size-1]; //inserting only the last element in already sorted order
int i,k;
for(i=size-2;i>=0 && arr[i]>L;i--)
{
arr[i+1]=arr[i];
shiftcount++;
}
arr[i+1]=L;
}
else
{
int L=arr[size-2]; //inserting only the last element in already sorted order
int i,k;
for(i=size-3;i>=0 && arr[i]>L;i--)
{
arr[i+1]=arr[i];
}
arr[i+1]=L;
System.out.println("Sorted Array After Insertion At Last: ");
printArray(arr,size);
}
}
public static void insertionSort(int [] arr, int size) //part2 implmentented
{
int i;
shiftcount=0;
printArray(arr,size);
for(i=2;i<size;i++)
{
System.out.println(" Step: " +(i-1) +"\n");
insertionLast(arr,i);
printArray(arr,size);
}
}
public static void printArray(int []arr,int size)
{
int k;
for(k=0;k<size-1;k++)
{
System.out.print(arr[k]+" ");
}
}
public static void main(String args[]) throws IOException
{
Scanner sc=new Scanner(System.in);
do
{ //menu driven according to the requirements
System.out.println("\n\nChoose the following options");
System.out.println("-----------------------------");
System.out.println("1: Insertion part #1");
System.out.println("2: Insertion part #2");
System.out.println("3: Quit");
System.out.println("-----------------------------");
gch=sc.nextInt();
System.out.println("Enter Sorted Numbers Except The Last Number, Followed By q:");
if(gch==1)
{
int i;
BufferedReader brn = new BufferedReader(new InputStreamReader(System.in));
String lns = brn.readLine();
String[] sts = lns.trim().split("\\s+");
int ar[]=new int[sts.length];
for (i = 0; i < sts.length-1; i++) {
ar[i] = Integer.parseInt(sts[i]);
}
insertionLast(ar,ar.length);
}
else if(gch==2)
{
int i;
BufferedReader brn = new BufferedReader(new InputStreamReader(System.in));
String lns = brn.readLine();
String[] sts = lns.trim().split("\\s+");
int ar[]=new int[sts.length];
for (i = 0; i < sts.length-1; i++) {
ar[i] = Integer.parseInt(sts[i]);
}
insertionSort(ar,ar.length);
System.out.println(" Total shift count: "+ shiftcount);
}
else if(gch==3)
{
System.out.println("Quiting...");
break;
}
}while(gch!=3);
}
}

Trending now
This is a popular solution!
Step by step
Solved in 2 steps









