[关闭]
@Arbalest-Laevatain 2018-12-28T03:23:32.000000Z 字数 966 阅读 495

快速排序测试

未分类


测试代码

  1. #include <iostream>
  2. #include "Sort.h"
  3. using namespace std;
  4. /*快速排序*/
  5. int flag01 = 0; //全局变量,来计数
  6. //一次划分函数
  7. int Part(RcdType rcd[], int low, int high)
  8. {
  9. rcd[0] = rcd[low];
  10. while (low<high)
  11. {
  12. while (low < high && rcd[high].key >= rcd[0].key)
  13. high--;
  14. rcd[low] = rcd[high];
  15. while (low < high && rcd[low].key <= rcd[0].key)
  16. low++;
  17. rcd[high] = rcd[low];
  18. }
  19. //此时low即为划分后枢轴应该在的位置
  20. rcd[low] = rcd[0];
  21. flag01++;
  22. return low;
  23. }
  24. void QSort(RcdType rcd[], int s, int t)
  25. {
  26. int mid;
  27. //枢轴位置
  28. if (s <= 0 || t <= 0)
  29. return;
  30. else if (s<t)
  31. {
  32. mid = Part(rcd, s, t);
  33. QSort(rcd, mid+1, t);
  34. QSort(rcd, s, mid-1);
  35. }
  36. }
  37. int QSort_num()
  38. {
  39. return flag01;
  40. }
  41. void out(RcdType rcd[],int n)
  42. {
  43. for (int i = 0; i < n; i++)
  44. cout << rcd[i].key<<" ";
  45. cout << endl;
  46. }
  47. RcdType rcd[10] = {0,9,8,7,6,5,4,3,2,1};
  48. RcdType rcd1[10] = { 0,6,8,7,5,9,4,3,2,1 };
  49. RcdType rcd2[10] = { 0,3,8,7,6,9,5,4,2,1 };
  50. int main()
  51. {
  52. out(rcd1,10);
  53. QSort(rcd1, 1, 10 - 1);
  54. out(rcd1, 10);
  55. cout << QSort_num() << endl;
  56. flag01 = 0;
  57. out(rcd2, 10);
  58. QSort(rcd2, 1, 10 - 1);
  59. out(rcd2, 10);
  60. cout << QSort_num() << endl;
  61. return 0;
  62. }

测试结果

image.png-6.5kB

image.png-7.1kB

有上面两次测试可见,当枢轴的值接近于待排序列的中位数时,快速排序性能较好。
为避免枢轴的值为最小最大值,可以前、后、中间三个记录的大小居中的记录为枢轴

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注