ch7_11.cpp
资源名称:c.rar [点击查看]
上传用户:puke2000
上传日期:2022-07-25
资源大小:912k
文件大小:1k
源码类别:

C#编程

开发平台:

Visual C++

  1. //**********************
  2. //**    ch7_11.cpp    **
  3. //**********************
  4. #include <iostream.h>
  5. void qsort(int[],int,int);
  6. void main()
  7. {
  8.   int array[]={55,2,6,4,11,12,9,73,26,37};
  9.   int len=sizeof(array)/sizeof(int);
  10.   for(int i=0; i<len; i++)    //原始顺序输出
  11.     cout <<array[i] <<",";
  12.   cout <<endl <<endl;
  13.   qsort(array,0,len-1);       //调用排序函数
  14.   for(int i=0; i<len; i++)    //排序结果输出
  15.     cout <<array[i]<<",";
  16.   cout <<endl;
  17. }
  18. void qsort(int a[],int left,int right)    //快速排序法
  19. {
  20.   int pivot=a[right],l=left,r=right,temp;
  21.   while(l<r){
  22.     temp=a[l], a[l]=a[r], a[r]=temp;  //交换
  23.     while(l<r && a[r]>pivot) --r;
  24.     while(l<r && a[l]<=pivot) ++l;
  25.   }
  26.   temp=a[left], a[left]=a[r], a[r]=temp;  //使得a[r]成为分界元
  27.   if(left<r-1) qsort(a,left,r-1);
  28.   if(r+1<right) qsort(a,r+1,right);
  29. }