我已经为数组列表编写了一个快速排序,就目前而言,逻辑似乎是合理的。我遇到的问题是交换元素。似乎正在发生的事情不是交换元素,而是用要交换的元素替换现有元素。一个示例运行以 [happy, apples, eat, food] 之类的列表开始,在排序运行之后,它会出现 [happy, happy, happy, food]。我确信我的错误很简单,但我已经盯着它看太久了,需要重新审视它。到目前为止,这是我的代码。提前致谢!
String pivot = list.get(0); // Choose the first element as the pivot
int low = first + 1; // Index for forward search
int high = last; // Index for backward search
while (high > low)
{ // Search forward from left
while (low <= high && list.get(low).compareTo(pivot) <= 0)
{
low++;
}
// Search backward from right
while (low <= high && list.get(high).compareTo(pivot) > 0)
{
high--;
}
// Swap two elements in the list
if (high > low)
{
String temp = list.get(high);
list.set(high,list.get(low));
list.set(low,temp);
}
}
while (high > first && list.get(high).compareTo(pivot) <= 0)
{
high--;
}
// Swap pivot with list[high]
if (list.get(high).compareTo(pivot) < 0)
{
list.set(first, list.get(high));
list.set(high,pivot);
return high;
}
else
{
return first;
}
}