3

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

2 Answers 2

2

I would suggest dropping the Sorter class altogether and add the functionality of the Sorter class as methods into DriverSorter. I say this because the way you are implementing Sorter does not create useful instances.

import java.util.Scanner;

public class DriverSort {

    public static void main(String[] args) {

        Scanner scan =new Scanner(System.in);

        // this makes more sense to put this at the start of the program
        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");
        choice = scan.nextInt();

        if (choice != 0) { // a simple if else statement will do just fine
            // must prompt user for the "input first"
            System.out.println("Enter the length vector to be modified: ");
            int size = scan.nextInt();
            // now actually get the vector
            int input[] = new int[size];
            for (int i = 0; i < size; i++) {
                System.out.println("Enter next array element: ");
                input[i] = scan.nextInt();
            }

            System.out.println("\nBefore Sorting: ");
            System.out.println(input); // use the builtin functionality
            // sort the array
            int[] output = insertionSort(input);
            System.out.println("\nAfter Sorting: ");
            System.out.println(output);
        } else { 
            System.out.println("Goodbye!");
            System.exit(0);
        }  
    }

    // returns a sorted list (add more detail here)
    // add a new input that tells what sort of sorting to do
    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;
    } 
}

Keeping the Sorter Class:

public class Sorter {
    private int vector; \\ private just means only things inside this class can affect this variable
    // now initializer 
    public Sorter(int[] input) {
        this.vector = input; \\ set our field to be equal to the vector you input when making an instance
    // so the call to make a Sorter object will now be "Sorter sorter = new Sorter(input);"
    }

    // make this act on vector instead
    public static int[] insertionSort() // no input because it can "see" our vector field
    {
        int[] copy = this.vector; // make a copy so you don't mess vector up before your finished
        for (int i = 1; i < copy.length; i++) 
        {
            int valueToSort = copy[i];
             int j = i;

            while (j > 0 && copy[j - 1] > valueToSort) 
            {
                copy[j] = copy[j - 1];
                j--;
            }//end while loop.

            // insert the element
            copy[j] = valueToSort;
        }//end for loop    

        this.vector = copy; // now replace old field with our sorted copy!
    }//end insertionSort          

    // this is an excellent way to be able to see "vector" without allowing other
    // mischievous programs to accidentally change "vector." This is very similar reasoning
    // to why you very frequently have fields be private. Read up on encapsulation - it's 
    // super useful.
    public void printArray(int[] input) 
    { 
    System.out.println(this.vector.toString());
    }

}

Sign up to request clarification or add additional context in comments.

6 Comments

The thing is the project calls for a sorter class and I'll be adding an option for Bubble and selection sort into the sorter class if I can ever get this first one working correctly. After changing my toString the output is showing this is the output now Before Sorting: [0, 0] After Sorting: [0, 0] [0, 0]
In that case create keep the sorter class but add a field ('int[] vector' placed right after the 'public class Sorter') a called vector or something. Have the initializer set the input vector to this field called vector. Then have the insertionSort take no inputs and have it act on the field 'vector'. Have you switched your code around to initialize input and size after the user inputs these values? If not this may be where you are running into issues.
I'm sorry but I'm not sure that I've learned how to do what you suggested yet. Either that or I just didn't understand. Yeah I changed my code, I edited it in the post as well.
Here is a link that will introduce you to fields. I will modify my post to show you what I meant.
Thank you both, I'm hoping I'm able to use a field, I'm not sure we've learned them. Also, vector is just a name you came up with correct? Vector can be named anything?
|
1

The first thing I see is

int size = input.length;
int input[] = new int[size];

Which is so illegal I stopped reading. Either hard-code the size, or prompt the user for it.

int size = 10; // <-- 10
int input[] = new int[size]; // <-- this is fine.

or

int input[] = new int[10]; // <-- 10
int size = input.length; // <-- this if also fine.

So, you want something like -

System.out.println("Please enter the number for a sorting "
    + "method or enter 0 to quit: ");
int choice = scan.nextInt();
System.out.println("How many numbers do you want to enter: ");
int size = scan.nextInt();
int input[] = new int[size];

9 Comments

Thanks Elliot, yeah that was what I was having trouble with. So that first part is saying a fixed array of size 10 and the second is saying a max of size 10 using the user input of any number under 10?
Actually that second way is how I originally had it but I kept getting an out of bounds error.
@user3862586 Ummm. No. The first is defining an array with a length of size and the second is defining size on the length of an array. They're not directly equivalent operations.
What I want is an array of size to be however many integers the user inputs
Oh I see, i'm an idiot. Thanks! I do have another question though. It works now but this is the output...Before Sorting: [I@7ea987ac After Sorting: [I@7ea987ac [I@7ea987ac
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.