当前位置:   article > 正文

C语言实现快速排序(三种)_快速排序c语言

快速排序c语言

第一种:

  1. #include<stdio.h>
  2. void Swap(int*a,int*b)
  3. {
  4. int tmp=*a;
  5. *a=*b;
  6. *b=tmp;
  7. }
  8. int PartSort1(int* a, int left, int right)//快排
  9. {
  10. int keyi = left;
  11. while (left < right)
  12. {
  13. //找小
  14. while (left < right && a[right] >= a[keyi])
  15. {
  16. --right;
  17. }
  18. //找大
  19. while (left < right && a[left] <= a[keyi])
  20. {
  21. ++left;
  22. }
  23. Swap(&a[left], &a[right]);
  24. }
  25. Swap(&a[keyi], &a[left]);
  26. return left;
  27. }
  28. void Quicksort(int*a,int begin,int end)
  29. {
  30. if(begin>=end)
  31. return 0;
  32. int key=PartSort1(a,begin,end);
  33. Quicksort(a,begin,key-1);
  34. Quicksort(a,key+1,end);
  35. }
  36. int main()
  37. {
  38. int a[10]={0,7,9,8,5,6,4,3,2,1};
  39. Quicksort(a,0,9);
  40. for(int i=0;i<10;i++)
  41. {
  42. printf("%d ",a[i]);
  43. }
  44. return 0;
  45. }

第二种:挖坑法

  1. #include<stdio.h>
  2. void Swap(int* a, int* b)
  3. {
  4. int tmp = *a;
  5. *a = *b;
  6. *b = tmp;
  7. }
  8. int PartSort2(int* a, int left, int right)//快排
  9. {
  10. int key = a[left];
  11. int pit = left;
  12. while (left < right)
  13. {
  14. while (left<right && a[right]>key)
  15. right--;
  16. a[pit] = a[right];
  17. pit = right;
  18. while (left < right && a[left] <key)
  19. left++;
  20. a[pit] = a[left];
  21. pit = left;
  22. }
  23. a[pit] =key;
  24. return pit;
  25. }
  26. void Quicksort(int* a, int begin, int end)
  27. {
  28. if (begin >= end)
  29. return 0;
  30. int key = PartSort2(a, begin, end);
  31. Quicksort(a, begin, key - 1);
  32. Quicksort(a, key + 1, end);
  33. }
  34. int main()
  35. {
  36. int a[10] = { 0,7,9,8,5,6,4,3,2,1 };
  37. Quicksort(a, 0, 9);
  38. for (int i = 0; i < 10; i++)
  39. {
  40. printf("%d ", a[i]);
  41. }
  42. return 0;
  43. }

第三种:

  1. #include<stdio.h>
  2. void Swap(int* a, int* b)
  3. {
  4. int tmp = *a;
  5. *a = *b;
  6. *b = tmp;
  7. }
  8. int PartSort3(int* a, int left, int right)//快排
  9. {
  10. int key = left;
  11. int prev = left;
  12. int cur = left + 1;
  13. while (cur <= right)
  14. {
  15. if (a[cur] < a[key]&& a[++prev] != a[cur])
  16. Swap(&a[prev], &a[cur]);
  17. cur++;
  18. }
  19. Swap(&a[prev], &a[key]);
  20. return prev;
  21. }
  22. void Quicksort(int* a, int begin, int end)
  23. {
  24. if (begin >= end)
  25. return 0;
  26. int key = PartSort3(a, begin, end);
  27. Quicksort(a, begin, key - 1);
  28. Quicksort(a, key + 1, end);
  29. }
  30. int main()
  31. {
  32. int a[10] = { 0,7,9,8,5,6,4,3,2,1 };
  33. Quicksort(a, 0, 9);
  34. for (int i = 0; i < 10; i++)
  35. {
  36. printf("%d ", a[i]);
  37. }
  38. return 0;
  39. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/278188
推荐阅读
相关标签
  

闽ICP备14008679号