c/c++语言开发共享C中的QuickSort无法按预期工作

我尝试在C中实现QuickSort,但没有得到正确的结果。 这是我写的程序。

#include int partition(int a[],int low,int high) { int pivot = a[high]; int temp; int i = low-1; int j=0; for(j=0;j<high-1;j++) { if(a[j]<=pivot) { i=i+1; temp = a[i]; a[i] = a[j]; a[j] = temp; } } temp = a[i+1]; a[i+1] = pivot; a[high] = temp; return (i+1); } void quick_sort(int a[],int low,int high) { if(low<high) { int q = partition(a,low,high); quick_sort(a,low,q-1); quick_sort(a,q+1,high); } } main() { int i,n,a[10]; printf("nEnter the number of elements in the array : "); scanf("%d",&n); printf("nEnter the elements in the array : "); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("nElements in the array before sorting : "); for(i=0;i<n;i++) { printf (" %d",a[i]); } quick_sort(a,0,n-1); printf("nElements in the array after sorting : "); for(i=0;i<n;i++) { printf (" %d",a[i]); } printf("n"); } 

我输入的输入为0,4,2,7但结果为4,0,7,2。 我无法找到此代码的问题。 有人能帮我吗 ?

    你的for循环应该是: for(j=low;j

    看看Coreman的算法简介,我认为这是直接的。

    见https://ideone.com/Ug​​ouy4

      以上就是c/c++开发分享C中的QuickSort无法按预期工作相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/522964.html

      (0)
      上一篇 2020年12月11日
      下一篇 2020年12月11日

      精彩推荐