Reputation: 127
I'm writing a program that takes a disk file, manually entered input, or a randomly generated list using a Comparable ArrayList, and uses the Bubble sort method to sort the array, while counting the swaps and compares that the method does. Currently I'm using this code:
public static void bubbleSort(ArrayList<Comparable> list)
{
int swaps = 0;
int compares = 0;
System.out.println("List before sorting: " + list);
for (int i = 0; i < list.size(); i++)
for (int j = 0; j < list.size() - 1; j++)
{
if (list.get(j).compareTo(list.get(j + 1)) == 0)
{
swaps++;
compares++;
Swap(list.get(j), list.get(j + 1));
}
else
{
compares++;
}
}
System.out.println("List after sorting: " + list);
System.out.println("The system compared " + compares + " time(s).");
System.out.println("The system swapped " + swaps + " time(s)");
}
However, after taking the input the program doesn't seem to sort the ArrayList at all. This is the output.
List before sorting: [605, 499, 935, 925, 91, 348, 11, 57, 655, 708, 982, 770, 600, 149, 832, 287, 209, 853, 677, 758, 785, 983, 956, 469, 123, 51, 335, 846, 313, 992, 239, 881, 841, 954, 411, 548, 873, 775, 261, 918, 420, 803, 817, 529, 568, 251, 339, 109, 387, 294, 516, 377, 19, 287, 928, 300, 167, 496, 672, 898, 437, 617, 271, 546, 896, 230, 50, 660, 229, 702, 217, 856, 835, 472, 181, 489, 948, 24, 725, 521, 380, 398, 9, 694, 14, 415, 818, 474, 437, 286, 788, 280, 414, 595, 433, 450, 815, 443, 75, 704, 804]
List after sorting: [605, 499, 935, 925, 91, 348, 11, 57, 655, 708, 982, 770, 600, 149, 832, 287, 209, 853, 677, 758, 785, 983, 956, 469, 123, 51, 335, 846, 313, 992, 239, 881, 841, 954, 411, 548, 873, 775, 261, 918, 420, 803, 817, 529, 568, 251, 339, 109, 387, 294, 516, 377, 19, 287, 928, 300, 167, 496, 672, 898, 437, 617, 271, 546, 896, 230, 50, 660, 229, 702, 217, 856, 835, 472, 181, 489, 948, 24, 725, 521, 380, 398, 9, 694, 14, 415, 818, 474, 437, 286, 788, 280, 414, 595, 433, 450, 815, 443, 75, 704, 804]
The system compared 10100 time(s).
The system swapped 0 time(s)
I'm confused as to why/how the program is comparing 10100 times and why it's not sorting the list. Some clarity would be much appreciated.
Upvotes: 2
Views: 1347
Reputation: 393936
Your Swap(list.get(j), list.get(j + 1));
has no way of swapping the two elements passed to it. In order for it to be able to swap them, you must pass the list
itself + the indices of the elements you wish to swap.
Or simply call
Collections.swap(list, j, j + 1)
Besides, as commented by Robby, you only attempt to swap equal elements.
if (list.get(j).compareTo(list.get(j + 1)) == 0)
should be
if (list.get(j).compareTo(list.get(j + 1)) > 0)
Upvotes: 3