[英]Insertion & Quick Sort on Array List of Objects
I could use some help with a Java Assignment, I've to write an insertion sort and quick sort to sort an arraylist of objects and have found myself stuck. 我可以在Java分配中使用一些帮助,我必须编写插入排序和快速排序来对对象的数组列表进行排序,发现自己陷入困境。 The sort's don't seem to give the output I expect, ie.
排序似乎没有提供我期望的输出,即。 sorting the elements into alphabetical order.
将元素按字母顺序排序。
--Insertion Sort-- Airbus A380, Titanic, Boxter, Concorde, Airbus A380 -插入排序-空中客车A380,泰坦尼克号,义和团,协和飞机,空中客车A380
--Quick Sort-- Enzo, Titanic, Concorde, Boxter, Airbus A380 -快速排序-恩佐,泰坦尼克号,协和飞机,拳击手,空中客车A380
The above are the outputs I get. 以上是我得到的输出。
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;
}
Try these fixes to the quick sort code: 尝试对快速排序代码进行以下修复:
while (list.get(i).compareTo(pivot) < 0 ) // < (not >)
// ...
while (list.get(j).compareTo(pivot) > 0 ) // > (not <)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.