Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Selection Sorting Arrays in Java

  1. Mar 22, 2005 #1
    So, I have to create a program that makes a new array with 20 slots, then it asks you to enter a value into each index, which I have here:

    Code (Text):

    import java.io.*;

    class ArrayLoop
        public static void main (String[] args) throws IOException
            int[] array = new int[20];
            for (int i = 0; i <= 19; i++)
                System.out.println("Assign a value to slot " + i + ".");
                array[i] = KeyIn.anInt();
            System.out.println("The values are: ");
            for (int j = 0; j <= 19; j++)
                System.out.print(array[j] + " ");
    Except I have to make it so that it sorts each value from smallest to largest and print that out in the last line. I'm supposed to use selection sort for this and I'm given the code:

    Code (Text):

    static void selection_sort(int a[])
        int i, min;
        for (i = 0; i < a.length; i++)
            min = find_minimum(a, i);
            swap(a, i, min);

    static int find_minimum (int a[], int i)
        int j; min = i;
        for (j = i + 1; j < a.length; j++)
        if (a[j] < a[min])
        min = j;
        return min;

    static void swap(int a[], int i, int j)
        int hold = a[i];
        a[i] = a[j];
        a[j] = hold;
    The problem is, I have no idea how to implement this code to my original program :/. So the question is, how do I use selection sort in that program? Any help would be appreciated.
  2. jcsd
  3. Mar 23, 2005 #2
    Copy and paste them into your class ArrayLoop and then because the methods are static you can just use the method selection_sort on your array.
  4. Mar 23, 2005 #3
    What would be the correct syntax for using the method on the array? I can't seem to get this to work.
  5. Mar 23, 2005 #4
    It depends where you put methods selection_sort(), find_minimum(), and swap().
    One way (that I wouldn't suggest) is to put those methods in your class ArrayLoop (copy and paste), parallel with the main() method. Then you could just write inside main:

    Code (Text):

    selection_sort( array );
    The other way is to put those methods in another class (say, SelectionSort). Then inside main you would write:

    Code (Text):

    SelectionSort.selection_sort( array );
    It's that simple!
  6. Mar 23, 2005 #5
    Oh, I see now. Thanks a lot.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?

Similar Discussions: Selection Sorting Arrays in Java
  1. Sorting techniques (Replies: 6)

  2. Big arrays (Replies: 13)

  3. Java Arrays (Replies: 22)

  4. Java q (Replies: 3)

  5. Java problem. (Replies: 4)