SelectionSort exercise

  1. Create a new public class called SelectionSortDemo in a package selectionsort.
  2. Copy and paste this code over any generated code.
  3. Code the swapElements and findMinPos methods.
  4. Then code the sort method by using the swapElements and findMinPos methods that you just created.
  5. Then run the main method and hope for the best.

Once you have this working, make sure you add your code to your Google site and document it fully. Write a clear explanation to your self of how each method works, in terms of its parameters and return value.

Then answer these concept questions:

  1. Could I declare SelectionSort public? Explain.
  2. Why are swapElements() and findMinPos() declared private? Why is sort() not declared private?
  3. In the SelectionSort object, I pass a reference to the numbers[] array from method to method. Explain how I could avoid having to do that.
package selectionsort;

public class SelectionSortDemo {
// This class only exists to test our SelectionSort object.

    public static void main(String[] args) {
        // Declare an array of ints that we will pass to the SelectionSort object
        int[] numbers = {6, 2, 7, 4, 5, 1, 3, 8, 0, 9};

        // Create a new SelectionSort object and pass the array to it for sorting
        SelectionSort selectionSort = new SelectionSort();

        // Print the numbers out to see if they're sorted
        for (int i = 0; i < numbers.length; i++) {
            System.out.print(numbers[i] + " ");

class SelectionSort {

    void sort(int[] numbers) {
        // This method should use findMinPos and swapElements to carry out
        // the selection sort algorithm.

    private int findMinPos(int[] numbers, int startIndex) {
        // This method returns the index of the lowest int in a sub-array
        // of numbers, starting from startIndex and going to the end of the 
        // array. e.g. findMinPos({1, 4, 0, 5, 2, 7, 6, 3}, 3) should
        // return a value of 1. Ensure that you understand why.

    private void swapElements(int[] numbers, int aIndex, int bIndex) {
        // This method exchanges the values of numbers[aIndex] and 
        // numbers[bIndex]. e.g. swapElements({2, 4, 6, 7, 5, 0, 1, 3}, 1, 3)
        // swaps the position of the 4 and the 7, leaving numbers as
        // {2, 7, 6, 4, 5, 0, 1, 3}.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s