Search code examples
javaselection-sort

Java Selection Sort, what is wrong with my code?


import java.util.Random;

public class Tester {
    public static void main(String[] args) {
        selectionSort(args);
    }

    private static void printArray(int[] anArray) {
        for (int i = 0; i < anArray.length; i++) {
            if (i > 0) {
                System.out.print(", ");
            }
            System.out.print(anArray[i]);
        }
    }


    public static void selectionSort(String[] args) {

        int i, x = 0;

        int l = 10;
        Random r = new Random(271);
        int array[] = new int[l];
        for (i = 0; i < l; i++) {
            array[i] = r.nextInt();
        }

        while (i < l) {

            for (int j = 1; j <= i; j++) {
                if (array[j] < array[x])
                    x = j;
            }

            i++;
        }
        printArray(array);
    }

}

Everything is fine I just cannot print it correctly. When I print I get "-1061221096, -349834974, -1279215928, 1452441141, -367008517, 638966200, -464597014, 1551135748, -446923224, 542496703" which is not correct. Each number should be under 271 I believe.


Solution

  • Try to replace this:

     Random r = new Random(271);
    

    With:

     Random r = new Random();
    

    And replace this:

     array[i] = r.nextInt();
    

    With:

     array[i] = r.nextInt(271);
    

    You can have output something like this under 271:

      18, 94, 189, 105, 32, 153, 68, 159, 178, 34