[英]Quick Sort, sort in Descending order, instead of Ascending
我已經寫了一個快速排序算法,它以升序對數組進行排序。 我正在嘗試更改程序,以便按降序對數組進行排序。 聽起來很簡單,但我不確定要更改程序的哪些區域。 謝謝。
public static void Quick_Sort(ref double[] data, int left,int right, ref int count)
{
int i;
int j;
double pivot;
double temp;
i = left;
j = right;
pivot = data[(left + right) / 2];
do
{
while ((data[i] < pivot) && (i < right)) i++;
count++;
while ((pivot < data[j]) && (j > left)) j--;
count++;
;
if (i <= j)
{
temp = data[i];
data[i] = data[j];
data[j] = temp;
i++;
j--;
count++;
}
} while (i <= j);
if (left < j) Quick_Sort(ref data, left, j, ref count, order);
if (i < right) Quick_Sort(ref data, i, right, ref count, order);
}
public static void QuickSort(ref double[] data, int size, int order)
{
int count = 0;
Quick_Sort(ref data, 0, data.Length - 1, ref count, order);
Console.WriteLine("\n Quick Sort\n Number of Elements: {0}\n Executed {1} times\n\n Worse-Case: O(n^2)\n Best-Case: O(n log n)\n Average-Case: O(n log n)",size, count);
}
將do-while循環中的while循環更改為:
while ((data[i] > pivot) && (i < right)) i++;
count++;
while ((pivot > data[j]) && (j > left)) j--;
count++;
在第一個循環中,將data[i] < pivot
更改為data[i] > pivot
,在第二個循環中,將pivot < data[j]
更改為pivot > data[j]
。
與樞軸比較時,您應該更改符號。
while ((data[i] > pivot) && (i < right))
{
i++;
}
count++;
while ((pivot < data[j]) && (j > left))
{
j--;
}
count++;
這樣就夠了嗎? (排序后)
var dataReversed = data.Reverse().ToArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.