[算法练习]快速排序的C语言实现

系统管理员 2022-07-05 15:28 259阅读 0赞
  1. #include <stdio.h>
  2. void quick_sort(int A[],int p,int r){
  3. if(p<r){
  4. int q=partition(A,p,r);
  5. quick_sort(A,p,q-1);
  6. quick_sort(A,q+1,r);
  7. }
  8. }
  9. int times=0;
  10. //basic function of quick sort
  11. int partition(int A[],int p,int r){
  12. /* assume A[r] as the benchmark;
  13. while A[cur] is move from A[p] to A[r]:
  14. if A[cur] is smaller than A[r], then exchange A[par] and A[cur];
  15. A[cur] move to next;
  16. at last, exchange A[r] and A[par];
  17. so that A[par] is sorted in the array A[],
  18. because the numbers before A[par] is smaller than it,
  19. and the numbers after A[par] is larger than it.
  20. */
  21. int cur=p,par=p;
  22. while(cur<r){
  23. if(A[cur]<A[r]){
  24. //exchange A[cur] and A[par] then par++
  25. int temp=A[cur];
  26. A[cur]=A[par];
  27. A[par]=temp;
  28. par++;
  29. }
  30. cur++;
  31. }
  32. //exchange A[r] and A[par]
  33. int temp=A[r];
  34. A[r]=A[par];
  35. A[par]=temp;
  36. printf("\nafter %d times:\t",++times);
  37. int i;
  38. for(i=0;i<10-1;i++){
  39. printf("%d ",A[i]);
  40. }
  41. return par;
  42. }
  43. int main(){
  44. int a[]={3,1,5,12,6,8,11,7,4,15};
  45. int length=sizeof(a)/sizeof(a[0]);//get length of a[]
  46. int i;
  47. printf("before:\t");
  48. for(i=0;i<length;i++){
  49. printf("%d ",a[i]);
  50. }
  51. quick_sort(a,0,length-1);
  52. printf("\nafter:\t");
  53. for(i=0;i<length;i++){
  54. printf("%d ",a[i]);
  55. }
  56. getchar();
  57. }

SouthEast

发表评论

表情:
评论列表 (有 0 条评论,259人围观)

还没有评论,来说两句吧...

相关阅读

    相关 快速排序算法C语言实现

    快速排序算法(C语言实现) 快速排序是一种基于比较的排序算法,它采用递归分治策略来排序一个序列。快速排序算法是所有基于比较的排序算法中,平均情况下表现最好的一种算法。快速排序