我目前正在编写一个程序,该程序采用Comparable ArrayList并使用插入排序对值进行排序。这是我目前的代码:
public static void insertionSort(ArrayList<Comparable> list)
{
int compares = 0;
System.out.println("List before sorting: " + list);
for (int index = 1; index < list.size(); index++)
{
Comparable key = list.get(index);
int position = index;
// Shift larger values to the right
compares += 2;
while (position > 0 && key.compareTo(list.get(position - 1)) < 0)
{
compares++;
list.set(position, position - 1);
position--;
}
list.set(position, key);
}
System.out.println("List after sorting: " + list);
System.out.println("The system compared " + compares + " time(s).");
}
当我使用填充了100个整数的随机ArrayList运行程序时,这是我的输出:
List before sorting: [104, 319, 617, 29, 930, 621, 83, 615, 437, 819, 957, 294, 190, 404, 780, 723, 281, 494, 202, 180, 272, 747, 536, 666, 268, 163, 573, 568, 575, 223, 879, 511, 656, 764, 941, 255, 165, 481, 167, 718, 871, 535, 461, 150, 127, 997, 301, 431, 343, 437, 136, 561, 483, 167, 956, 315, 893, 127, 916, 973, 376, 405, 194, 134, 381, 122, 839, 707, 369, 778, 154, 485, 88, 2, 900, 30, 722, 302, 301, 439, 347, 847, 111, 353, 17, 336, 599, 966, 886, 76, 692, 587, 37, 958, 560, 909, 122, 381, 851, 956, 698]
List after sorting: [29, 0, 1, 2, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 560, 93, 122, 95, 381, 698, 98, 99]
The system compared 487 time(s).
这段代码出了什么问题,为什么它似乎从列表中删除整数,而这个列表完全无法正常工作?