[英]Insertion & Quick Sort on Array List of Objects
我可以在Java分配中使用一些幫助,我必須編寫插入排序和快速排序來對對象的數組列表進行排序,發現自己陷入困境。 排序似乎沒有提供我期望的輸出,即。 將元素按字母順序排序。
-插入排序-空中客車A380,泰坦尼克號,義和團,協和飛機,空中客車A380
-快速排序-恩佐,泰坦尼克號,協和飛機,拳擊手,空中客車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;
}
嘗試對快速排序代碼進行以下修復:
while (list.get(i).compareTo(pivot) < 0 ) // < (not >)
// ...
while (list.get(j).compareTo(pivot) > 0 ) // > (not <)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.