SORTING ARRAYS IN JAVA

Barbara Jones

Total Post:13

Points:91
Posted by  Barbara Jones
 916  View(s)
Ratings:
Rate this:

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?

  1. Elena Glibart

    Post:42

    Points:296
    Re: sorting arrays in java

    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

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!