1
我有這樣的代碼,我使用的算法我在維基百科上找到寫道:鑑於此輸入快速排序算法不排序最終元素?
public static void quicksort(int[] arr, int low, int hi)
{
if(low < hi)
{
int pivot = part(arr, low, hi);
quicksort(arr, low, pivot - 1);
quicksort(arr, pivot + 1, hi);
}
}
public static int part(int[] arr, int low, int hi)
{
int pivot = arr[hi];
int i = low;
for(int j = low; j < hi - 1; j++)
{
if(arr[j] <= pivot)
{
swap(arr, i, j);
i++;
}
}
swap(arr, i, hi);
return i;
}
public static void swap(int[] ar, int a, int b)
{
int temp = ar[a];
ar[a] = ar[b];
ar[b] = temp;
}
:
31, 5, 5, 5, 5, 4, 4, 4, 5, 4
,不要指望得到:
4, 4, 4, 4, 5, 5, 5, 5, 5, 31
而是我得到:
4, 4, 4, 4, 5, 5, 5, 5, 31, 5
什麼給?
我打電話與初始排序:quicksort(array, 0, array.Length - 1);
考慮嘗試'快速排序(數組,0,array.Length)' –
當我這樣做時,超出數組的邊界。零索引意味着較高的索引比長度小一個。 –