我写了这个lomuto-type函数用于快速排序,但它没有用。分段错误发生在运行时。我的错误在哪里?
int partition(int *a, int low, int high)
{
int pos = low, i, pivot = a[low], temp;
for (i = low + 1; i <= high; i++)
if(a[i] <= pivot) {
pos++;
temp = a[pos];
a[pos] = a[i];
a[i] = temp;
}
return pos;
}
void quickS(int *a, int low, int high)
{
while (low < high) {
int pivot = partition(a, low, high);
quickS(a, low, pivot - 1);
low = pivot + 1;
}
}
答案 0 :(得分:0)
试试这个:
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int data[], int l, int h)
{
int i;
int p;
int firsthigh;
p = h;
firsthigh = l;
for (i = l; i < h; ++i)
{
if (data[i] < data[p])
{
swap(&data[i], &data[firsthigh]);
firsthigh++;
}
}
swap(&data[p], &data[firsthigh]);
return firsthigh;
}
答案 1 :(得分:0)
枢轴(a [低])似乎需要交换。
验证码:
#include<stdio.h>
int partition(int *a, int low, int high){
int pos = low, i, pivot = a[low], temp;
for (i = low + 1; i <= high; i++)
if(a[i] <= pivot) {
pos++;
temp = a[pos];
a[pos] = a[i];
a[i] = temp;
}
return pos;
}
int main(){
int data[] = { 10, 1, 2, 3 };
int i, retvalue;
retvalue = partition(data, 0, 4-1);
printf("%d\n", retvalue);
for(i = 0; i< 4; ++i)
printf("%d ", data[i]);//10 1 2 3 : N/C
printf("\n");
return 0;
}
据信,如果分区函数这样怀疑导致堆栈溢出,那么重复调用就无法正常工作。
答案 2 :(得分:0)
试试这个
int partition (int arr[], int low, int high )
{
int x = arr[high];
int i = (low - 1);
for (int j = l; j <= high- 1; j++)
{
if (arr[j] <= x)
{
i++;
swap (&arr[i], &arr[j]);
}
}
swap (&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int A[], int low, int high)
{
if (low < high)
{
int p = partition(A, low, high);
quickSort(A, low, p - 1);
quickSort(A, p + 1, high);
}
}
答案 3 :(得分:0)
在获得枢轴的正确位置后,您需要将枢轴放在该位置,然后返回位置。