|
你这个代码好像抄错了吧,我编译了一下,发现是错的。
我去到了啊哈磊的博客下面找到了正确的代码,如下:
- #include <stdio.h>
- int a[101],n;//定义全局变量,这两个变量需要在子函数中使用
- void quicksort(int left,int right)
- {
- int i,j,t,temp;
- if(left>right)
- return;
-
- temp=a[left]; //temp中存的就是基准数
- i=left;
- j=right;
- while(i!=j)
- {
- //顺序很重要,要先从右边开始找
- while(a[j]>=temp && i<j)
- j--;
- //再找右边的
- while(a[i]<=temp && i<j)
- i++;
- //交换两个数在数组中的位置
- if(i<j)
- {
- t=a[i];
- a[i]=a[j];
- a[j]=t;
- }
- }
- //最终将基准数归位
- a[left]=a[i];
- a[i]=temp;
-
- quicksort(left,i-1);//继续处理左边的,这里是一个递归的过程
- quicksort(i+1,right);//继续处理右边的 ,这里是一个递归的过程
- }
- int main()
- {
- int i,j,t;
- //读入数据
- scanf("%d",&n);
- for(i=1;i<=n;i++)
- scanf("%d",&a[i]);
- quicksort(1,n); //快速排序调用
-
- //输出排序后的结果
- for(i=1;i<=n;i++)
- printf("%d ",a[i]);
- getchar();getchar();
- return 0;
- }
复制代码
我画一个图给你演示一下。箭头表示的是方向,红色数字表示的是顺序。
还有,我把这个代码改了一下,输出了某些中间结果,用不同的数据去测试一下我的这个代码吧,或许可以帮助你的理解。
- #include <stdio.h>
- int a[101],n;
- int cnt=0;//这个cnt就是帮助你理解第几次调用函数或者什么的
- void quicksort(int left,int right)
- {
- int i,j,t,temp;
-
- printf("left:%d right:%d cnt:%d\n",left,right,cnt);cnt++;//注意这里
-
- if(left>right)
- return;
-
- temp=a[left];
- i=left;
- j=right;
- while(i!=j)
- {
- while(a[j]>=temp && i<j)
- j--;
- while(a[i]<=temp && i<j)
- i++;
- if(i<j)
- {
- t=a[i];
- a[i]=a[j];
- a[j]=t;
- }
- }
- a[left]=a[i];
- a[i]=temp;
- quicksort(left,i-1);
-
- printf("left:%d right:%d cnt:%d\n",left,right,cnt);cnt++;//注意这里
-
- quicksort(i+1,right);
-
- printf("left:%d right:%d cnt:%d\n",left,right,cnt);cnt++;//注意这里
- }
- int main()
- {
- int i,j,t;
- scanf("%d",&n);
- for(i=1;i<=n;i++)
- scanf("%d",&a[i]);
- quicksort(1,n);
-
- for(i=1;i<=n;i++)
- printf("%d ",a[i]);
- getchar();getchar();
- return 0;
- }
复制代码
|
-
1.png
(131.47 KB, 下载次数: 12)
|