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;
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With