[英]Error in QUICKSORT . Unable to fix the error
I was working on QUICKSORT and I wrote this whole program by myself.我正在开发 QUICKSORT,我自己编写了整个程序。 The code is as follows
代码如下
#include<stdio.h>
#include<stdlib.h>
void quicksort(int*,int,int);
int partition(int*,int,int);
swap(int*,int*);
int main()
{
int *arr,n,i;
printf("\nEnter the size of the array");
scanf("%d",&n);
arr=(int*)malloc(n*sizeof(int));
printf("\nEnter the elements of the array one by one");
for(i=0;i<n;i++)
{
scanf("%d",arr+i);
}
quicksort(arr,0,n-1);
printf("\nThe Sorted Array is as follows");
for(i=0;i<n;i++)
{
printf("%d",*(arr+i));
}
return 0;
}
void quicksort(int* arr,int a,int b)
{
int c;
if(a<b)
c=partition(arr,a,b);
quicksort(arr,a,c-1);
quicksort(arr,c+1,b);
}
int partition(int* arr,int a,int b)
{
int x,y,index=*(arr+b);
x=a,y=b-1;
while(x<y)
{
if(*(arr+x)<index)
{
x++;
}
if(index<*(arr+y))
{
y--;
}
swap((arr+x),(arr+y));
}
swap((arr+x),(arr+b));
return x;
}
swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
I tried to run this program but after the array input it says segmentation error.我试图运行这个程序,但在数组输入之后它说分段错误。 I spent few minutes looking at the code and checked the code again and again but I do not seem to move anywhere.
我花了几分钟查看代码并一遍又一遍地检查代码,但我似乎没有移动任何地方。 can someone tell me where is the mistake.
谁能告诉我错误在哪里。
What should be happening if a is greater than or equal to b?如果 a 大于或等于 b 会发生什么? this should solve the segmentation problem.
这应该解决分割问题。
void quicksort(int* arr, int a, int b) {
int c;
if (a < b) {
c = partition(arr,a,b);
quicksort(arr, a, c-1);
quicksort(arr, c+1, b);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.