[英]quicksort using an arraylist java
我已經為arraylist寫了一個快速排序,從目前的角度來看,邏輯似乎很合理。 我遇到的問題是元素交換。 似乎正在發生的事情不是交換元素,而是將現有元素替換為要交換的元素。 一個示例運行以[快樂,蘋果,飲食,食物]之類的列表開始,然后在排序運行后顯示為[快樂,快樂,幸福,食物]。 我確定我的錯誤很簡單,但是我盯着它看了太久了,需要重新審視。 到目前為止,這是我的代碼。 提前致謝!
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;
}
}
是的,我認為錯誤很簡單。 嘗試這個
String tempHigh = list.get(high);
String tempLow = list.get(low);
list.set(high, tempLow);
list.set(low, tempHigh);
因為在Java中,賦值是通過引用完成的。 在您的代碼中,您只需將高值設置為高位和低位。 當您將數據透視表與列表交換時,同樣的事情也會發生
問題(將樞紐選擇固定為使用list.get(first)
)是
while (high > first && list.get(high).compareTo(pivot) <= 0)
在這一點上,在索引high
之前(包括索引high
)的所有元素(按字典順序)小於或等於樞軸。 從而
while(high> first && list.get(high).compareTo(pivot)<= 0){
high--;
}
可以縮寫為high = first
。
這就解釋了第一個元素與
String pivot = list.get(0);
數據透視選擇,因為在您的示例中,索引0處的元素最大,因此
if (list.get(high).compareTo(pivot) < 0)
{
list.set(first, list.get(high));
list.set(high,pivot);
return high;
}
采取分支, list.set(first, list.get(high));
什么都不做,因為high == first
,然后list.set(high,pivot);
將樞軸復制到索引high (== first)
。
您在問題線上需要的是
if (list.get(high).compareTo(pivot) > 0) {
--high;
}
如果在第一個分區循環之后索引high
的元素大於樞軸,則之前的元素小於或等於樞軸。 否則, high
是不大於樞軸的元素的最大索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.