Home > DeveloperSection > Forums > sorting arrays in java
Barbara Jones

Total Post:13

Points:91
Posted on    November-13-2014 12:31 AM

 Java Array  Sorting 
Ratings:


 1 Reply(s)
 591  View(s)
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?



Elena Glibart
Elena Glibart

Total Post:33

Points:233
Posted on    November-13-2014 3:39 AM

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]);

    }


Don't want to miss updates? Please click the below button!

Follow MindStick