我可以使用Java Assignment的一些帮助,我要写一个插入排序和快速排序来对对象的arraylist进行排序,并发现自己陷入困境。排序似乎没有给出我期望的输出,即。将元素按字母顺序排序。
- 插入排序 - 空客A380, 泰坦尼克号, BOXTER, 协和广场, 空客A380
- 快速排序 - 恩佐, 泰坦尼克号, 协和广场, BOXTER, 空客A380
以上是我得到的输出。
protected ArrayList<Vehicle> insertionSort(ArrayList<Vehicle> list)
{
ArrayList<Vehicle> sorted = new ArrayList<Vehicle>(list);
int n = list.size();
for (int j = 1; j < n; j++)
{
Vehicle key = list.get(j);
Vehicle pivot = list.get(j-1);
int i = j-1;
for(i = j - 1; (i >= 0) && (pivot.compareTo(key)) > 0; i--) // Smaller values are moving down
{
sorted.set(i, list.get(i));
}
sorted.set(i+1, key); // Put the key in its proper location
}
return sorted;
}
protected ArrayList<Vehicle> quickSort(ArrayList<Vehicle> list, int low, int high)
{
ArrayList<Vehicle> sorted = new ArrayList<Vehicle>(list);
int i = low; int j = high;
// Get the pivot element from the middle of the list
Vehicle pivot = list.get(low + (high - low) / 2);
// Divide into two lists
while (i <= j) {
// If the current value from the left list is smaller then the pivot
// element then get the next element from the left list
while (list.get(i).compareTo(pivot) > 0 )
{
i++;
}
// If the current value from the right list is larger then the pivot
// element then get the next element from the right list
while (list.get(j).compareTo(pivot) < 0 )
{
j--;
}
// If we have found a value in the left list which is larger than
// the pivot element and if we have found a value in the right list
// which is smaller then the pivot element then we exchange the
// values.
// As we are done we can increase i and j
if (i <= j) {
sorted.set(i,list.get(j));
sorted.set(j,list.get(i));
i++;
j--;
}
}
if (low < j)
quickSort(sorted, low, j);
if (i < high)
quickSort(sorted, i, high);
return sorted;
}
答案 0 :(得分:0)
尝试对快速排序代码进行以下修复:
while (list.get(i).compareTo(pivot) < 0 ) // < (not >)
// ...
while (list.get(j).compareTo(pivot) > 0 ) // > (not <)