I got this bubblesort in college and am trying to run it! It's supposed to sort the numbers in order of size, smallest to largest. Any help would be appreciated. (It comes from Derek Banas on YouTube). Do you know why it doesn't work?
public class ListForSorting {
int arraySize = 10;
int[] myArray = { 10, 12, 3, 4, 50, 60, 7, 81, 9, 100 };
public void printArray() {
System.out.println("----------");
for (int i = 0; i < arraySize; i++) {
System.out.print("| " + i + " | ");
System.out.println(myArray[i] + " |");
System.out.println("----------");
}
}
public static void main(String[] args) {
ListForSorting list = new ListForSorting();
list.printArray();
list.bubbleSort();
list.printArray();
}
public void bubbleSort() {
for (int i = arraySize - 1; i > 1; i--) {
for (int j = 0; j < i; j++) {
if (myArray[j] < myArray[j + 1])
swap(j, j + 1);
}
}
}
public void swap(int indexOne, int indexTwo) {
int temp = myArray[indexOne];
myArray[indexOne] = myArray[indexTwo];
temp = myArray[indexTwo];
}
}
Output:
----------
| 0 | 10 |
----------
| 1 | 12 |
----------
| 2 | 3 |
----------
| 3 | 4 |
----------
| 4 | 50 |
----------
| 5 | 60 |
----------
| 6 | 7 |
----------
| 7 | 81 |
----------
| 8 | 9 |
----------
| 9 | 100 |
----------
----------
| 0 | 81 |
----------
| 1 | 100 |
----------
| 2 | 100 |
----------
| 3 | 100 |
----------
| 4 | 100 |
----------
| 5 | 100 |
----------
| 6 | 100 |
----------
| 7 | 100 |
----------
| 8 | 100 |
----------
| 9 | 100 |
Thanks!