I'm trying to write a sorting program that will ask a user what type of sorting method to use (insertion, bubble, selection) and then ask him to enter integers to sort.
I think I have everything correct except for the array: I want the size of the array to be big as the number of integers the user enters, but I do not seem to be doing it correctly.
In the sorting class, where the insertionSort method is, should I have the input parameter named like that (through out the algorithm) or should I make a generic name like "arr"?
Where can I improve and correct my code?
Thanks for any help!!
DriverSort class:
import java.util.Scanner;
public class DriverSort
{
public static void main(String[] args)
{
Scanner scan =new Scanner(System.in);
Sorter sorter = new Sorter();
int choice;// variable which says which sorting algorithm to use
System.out.println("1-Insertion sort\n"
+"2-Selection sort\n"
+ "3-Bubble sort\n"
+ "0-quit\n");
int size = scan.nextInt();
int input[] = new int[size];
System.out.println("Please enter the number for a sorting method or enter 0 to quit: ");
size = scan.nextInt();
System.out.println("\nBefore Sorting: ");
sorter.printArray(input);
// sort the array
Sorter.insertionSort(input);
System.out.println("\nAfter Sorting: ");
sorter.printArray(input);
switch (choice)
{
case 0:
System.out.println("Goodbye!");
System.exit(0);
break;
case 1:
Sorter.insertionSort(input);
sorter.printArray(input);
break;
}
}
}
Sorter class:
public class Sorter
{
public static int[] insertionSort(int[] input)
{
for (int i = 1; i < input.length; i++)
{
int valueToSort = input[i];
int j = i;
while (j > 0 && input[j - 1] > valueToSort)
{
input[j] = input[j - 1];
j--;
}//end while loop.
// insert the element
input[j] = valueToSort;
}//end for loop
return input;
}//end insertionSort
public void printArray(int[] input)
{
System.out.println(input.toString());
}
}