我从这本书中找到了快速排序算法
这是算法
QUICKSORT (A, p, r)
if p < r
q = PARTITION(A, p, r)
QUICKSORT(A, p, q-1)
QUICKSORT(A, q+1, r)
PARTITION(A, p, r)
x=A[r]
i=p-1
for j = p to r - 1
if A <= x
i = i + 1
exchange A[i] with A[j]
exchange A[i+1] with A[r]
return i + 1
我做了这个c#代码:
private void quicksort(int[] input, int low, int high)
{
int pivot_loc = 0;
if (low < high)
pivot_loc = partition(input, low, high);
quicksort(input, low, pivot_loc - 1);
quicksort(input, pivot_loc + 1, high);
}
private int partition(int[] input, int low, int high)
{
int pivot = input[high];
int i = low - 1;
for (int j = low; j < high-1; j++)
{
if (input[j] <= pivot)
{
i++;
swap(input, i, j);
}
}
swap(input, i + 1, high);
return i + 1;
}
private void swap(int[] ar, int a, int b)
{
temp = ar[a];
ar[a] = ar[b];
ar[b] = temp;
}
private void print(int[] output, TextBox tbOutput)
{
tbOutput.Clear();
for (int a = 0; a < output.Length; a++)
{
tbOutput.Text += output[a] + " ";
}
}
当我像这样调用函数时,quicksort(arr,0,arr.Length-1);
我得到这个错误An unhandled exception of type 'System.StackOverflowException' occurred
,它传递了空数组......当像这样调用函数时,我在这一行quicksort(arr,0,arr.Length);
得到错误,但数组成功传递。Index was outside the bounds of the array.
int pivot = input[high];
我也想像这样打印它,print(input,tbQuick);
但是在哪里放置它以便在快速排序完成时打印?