sorting arrays in java

I`ve been trying to bubble sort an array in java for some time now, but every time it just does a few and then it follows the array list.

public void mysort() {
    Random randomNumbers = new Random();
    int randomArray[] = new int[20];
    for (int j = 0; j <= 19; j++) {
        randomArray[j] = randomNumbers.nextInt(200 + 1);
        for (int k = 1; k < 20; k++) {
            if (randomArray[k - 1] < randomArray[k]) {
                int hjelp = randomArray[k - 1];
                randomArray[k - 1] = randomArray[k];
                randomArray[k] = hjelp;
            }
        }
    }
    for (int i = 0; i <= 19; i++) {
        System.out.println(randomArray[i]);
    }
}

How do I make my bubble sort work properly?

Last updated:11/13/2014 3:39:50 AM

1 Answers

Elena Glibart
Elena Glibart

You should populate the array first, and THEN call the sort. You're 'sorting' the array 20 times, while it's still incomplete.

public void mysort() {
    Random randomNumbers = new Random();
    int randomArray[] = new int[20];
    for (int j = 0; j < randomArray.length; j++) {
        randomArray[j] = randomNumbers.nextInt(200) + 1;
    }
    for (int i = 0; i < randomArray.length; i++) {
        for (int k = 1; k < randomArray.length; k++) {
            if (randomArray[k - 1] < randomArray[k]) {
                int hjelp = randomArray[k - 1];
                randomArray[k - 1] = randomArray[k];
                randomArray[k] = hjelp;
            }
        }
    }
    for (int i = 0; i < randomArray.length; i++) {
        System.out.println(randomArray[i]);
    }

Answer