将冒泡排序与 Comparable ArrayLists 结合使用

Using Bubble sort with Comparable ArrayLists

我正在编写一个程序,该程序采用磁盘文件、手动输入或使用 Comparable ArrayList 随机生成的列表,并使用冒泡排序方法对数组进行排序,同时计算交换并比较方法呢。目前我正在使用此代码:

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)");
    }

但是,在接受输入后,程序似乎根本没有对 ArrayList 进行排序。这是输出。

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)

我对 why/how 程序正在比较 10100 次以及为什么不对列表进行排序感到困惑。一些清晰度将不胜感激。

您的 Swap(list.get(j), list.get(j + 1)); 无法交换传递给它的两个元素。为了使其能够交换它们,您必须传递 list 本身 + 您希望交换的元素的索引。

或直接致电

Collections.swap(list, j, j + 1)

此外,正如 Robby 所评论的,您只尝试交换相等的元素。

if (list.get(j).compareTo(list.get(j + 1)) == 0)

应该是

if (list.get(j).compareTo(list.get(j + 1)) > 0)