3

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;

0

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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++)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.