Freud
Freud

Reputation: 41

Bubble sort function does not sort the given array

So basically, I have set up bubblesort algorithm and weirdly enough it does not return the sorted array just the unsorted array.

The given array;

int[] array = { 20, 5, 1, 6, 23, 52, 15, 12 };

Bubble sort algorithm;

public static int[] sort_array(int[] array) {

    int [] sorted = array;
    int temp = 0;

    for (int i = 0; i < sorted.length - 1; i++) {
        for (int j = 0; i < sorted.length - i - 1; i++) {
            if (sorted[j] > sorted[j + 1]) {
                temp = sorted[j];
                sorted[j] = sorted[j + 1];
                sorted[j + 1] = temp;
            }
        }
    }
    return sorted;
}

Also made an array return method;

public static void return_list(int[] array) {

    for (int i = 0; i < array.length; i++) {
        System.out.println(array[i]);
    }
}

After the methods are used it just returns me the unsorted array.

int[] array = { 20, 5, 1, 6, 23, 52, 15, 12 };

sort_array(array);

return_list(array);

Output = 20, 5, 1, 6, 23, 52, 15, 12;

Upvotes: 3

Views: 151

Answers (3)

Hyperion
Hyperion

Reputation: 1

There is a bug: Replace i by j here ->for(int j=0;i(here)

Upvotes: 0

Sakis
Sakis

Reputation: 41

You are checking for the value of i every time as well as increasing its value on every iteration of

for (int j = 0; i < sorted.length - i - 1; i++)

Upvotes: 0

Otomatonium
Otomatonium

Reputation: 211

Duplicating an array (assuming you want to keep the original one)

First, you're not copying array into sorted here. You're copying a reference of array to sorted, so any change to the contents of sorted will also be seen in array

int [] sorted = array;

Do this to instantiate a new array sorted and copy contents from array into it: Make copy of array

There are several ways (Arrays.copyOf, clone, etc.) to do an array copy. For example:

int[] sorted = Arrays.copyOf(array, array.length);

Sorting bug

Also, it looks like there may be a bug in your for loops. You're not iterating through j in this line

for (int j = 0; i < sorted.length - i - 1; i++)

So, the reason it looks like you're getting an unsorted array is that the array isn't being sorted correctly.

Upvotes: 4

Related Questions