Your swap
function was wrong. It should be like this:
public void swap(int indexOne, int indexTwo) {
int temp = myArray[indexOne];
myArray[indexOne] = myArray[indexTwo];
myArray[indexTwo] = temp;
}
Also, bubblesort
function has an error. Counter i
should go down to 1
not to 2
, or else your first element wont be sorted as it should be:
public void bubbleSort() {
for (int i = arraySize - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (myArray[j] < myArray[j + 1])
swap(j, j + 1);
}
}
}
Now it outputs:
----------
| 0 | 10 |
----------
| 1 | 12 |
----------
| 2 | 3 |
----------
| 3 | 4 |
----------
| 4 | 50 |
----------
| 5 | 60 |
----------
| 6 | 7 |
----------
| 7 | 81 |
----------
| 8 | 9 |
----------
| 9 | 100 |
----------
----------
| 0 | 100 |
----------
| 1 | 81 |
----------
| 2 | 60 |
----------
| 3 | 50 |
----------
| 4 | 12 |
----------
| 5 | 10 |
----------
| 6 | 9 |
----------
| 7 | 7 |
----------
| 8 | 4 |
----------
| 9 | 3 |
----------
If you want from smallest number to biggest, just change if
condition in bubblesort
function:
public void bubbleSort() {
for (int i = arraySize - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (myArray[j] > myArray[j + 1])
swap(j, j + 1);
}
}
}
Now, the output would be:
----------
| 0 | 10 |
----------
| 1 | 12 |
----------
| 2 | 3 |
----------
| 3 | 4 |
----------
| 4 | 50 |
----------
| 5 | 60 |
----------
| 6 | 7 |
----------
| 7 | 81 |
----------
| 8 | 9 |
----------
| 9 | 100 |
----------
----------
| 0 | 3 |
----------
| 1 | 4 |
----------
| 2 | 7 |
----------
| 3 | 9 |
----------
| 4 | 10 |
----------
| 5 | 12 |
----------
| 6 | 50 |
----------
| 7 | 60 |
----------
| 8 | 81 |
----------
| 9 | 100 |
----------
Edit: performance
You can make this faster by "checking" if inner loop did at least one swap. If it didn't that means you can exist the outer loop since it finished and save time for the rest of outer loop iteration.