A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Beacon 中级黑马   /  2014-10-23 14:20  /  1288 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

整理了一下快速排序。。。 大家一起学习!!!
  1. void sort(int arr[], int l, int r)
  2. {
  3.         int i = l;
  4.         int j = r;
  5.         int x = arr[i];
  6.         if(l < r)
  7.         {
  8.                 while(i < j)
  9.                 {
  10.                         while((i<j) && (arr[j]>x))
  11.                                 j--;
  12.                         arr[i] = arr[j];
  13.                         while((i<j) && (arr[i]<x))
  14.                                 i++;
  15.                         arr[j] = arr[i];
  16.                 }
  17.                 arr[i] = x;
  18.                 sort(arr, l, i-1);
  19.                 sort(arr, i+1, r);
  20.         }
  21. }

  22. int main()
  23. {
  24.         int i;
  25.         int arr[] = {18, 2, 15, 29, 12, 60};
  26.         sort(arr, 0, 5);
  27.         for(i = 0; i < 6; i++)
  28.                 cout << arr[i] << " ";
  29.         cout << endl;
  30.         return 0;
  31. }
复制代码


评分

参与人数 1技术分 +1 收起 理由
星河鹭起 + 1

查看全部评分

4 个回复

倒序浏览
魔法少年十三 来自手机 中级黑马 2014-10-23 22:55:12
沙发
这个输出语句明显是c++
回复 使用道具 举报
我记得好像还有更快的快排语句。。
回复 使用道具 举报
这不是递归排序么?
回复 使用道具 举报
  1. 快排
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<time.h>
  5. #define MAX  100
  6. /*
  7. 快速排序算法的两个主要步骤,分割(Partition和QuickSort)
  8. */
  9. int Partition(int A[],int p,int q);
  10. int QuickSort(int A[],int p,int q);
  11. int test();
  12. int main()
  13. {
  14. test();
  15. return 0;
  16. }
  17. /*
  18. 一个很简单的测试函数
  19. */
  20. int test()
  21. {
  22. int a[MAX];
  23. int i;
  24. srand((int)time(0));
  25. for(i = 0;i<MAX;i++)
  26. {
  27.   
  28.   a[i] = rand();
  29. }
  30. for(i = 0;i<MAX;i++)
  31.   printf("%d\t",a[i]);
  32. printf("\n");
  33. QuickSort(a,0,MAX-1);
  34. for(i = 0;i<MAX;i++)
  35.   printf("%d\t",a[i]);
  36. printf("\n");

  37. }
  38. /*
  39. Partition步骤中哨兵选取的是最后一个元素作为哨兵
  40. */
  41. int Partition(int A[],int p,int q)
  42. {
  43. int i,j,x,t;
  44. x = A[q];
  45. i = p-1;
  46. for (j = p;j<=q;j++)
  47.   if(A[j] < x)
  48.   {
  49.    i++;
  50.    t = A[j];
  51.    A[j] = A[i];
  52.    A[i] = t;
  53.   }
  54. A[q] = A[i+1];
  55. A[i+1] = x;
  56. return i+1;
  57. }
  58. /*
  59. 递归调用的QuickSort程序
  60. */
  61. int QuickSort(int A[],int p,int r)
  62. {
  63. if(p<r)
  64. {
  65.   int q = Partition(A,p,r);
  66.   QuickSort(A,p,q-1);
  67.   QuickSort(A,q+1,r);
  68. }
  69. }
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马