快排实现时候的一个逻辑错误
1 #include"header_file.h" 2 using namespace std; 3 4 void swap(int a,int b) 5 { 6 int t; 7 t=a; 8 a=b; 9 b=t; 10 } 11 12 void quick_sort(int a[],int low,int high) 13 { 14 15 if(low>=high) 16 return; 17 18 int first; 19 int last; 20 first=low; 21 last=high; 22 23 int x; 24 x=a[low]; 25 26 27 while(low<high) 28 { 29 while(low<high&&a[high]>=x) 30 { 31 high--; 32 } 33 swap(a[low],a[high]); 34 35 cout<<i<<" "<<low<<" low"<<" "<<high<<endl; 36 37 while(low<high&&a[low]<=x) 38 { 39 low++; 40 } 41 swap(a[high],a[low]); 42 cout<<i<<" "<<low<<" high"<<" "<<high<<endl; 43 } 44 if(first<low-1) 45 quick_sort(a,first,low-1); 46 if(last>low+1) 47 quick_sort(a,low+1,last); 48 } 49 50 int main(void) 51 { 52 int a[7]={4,3,6,7,2,1,5}; 53 quick_sort(a,0, sizeof(a) / sizeof(a[0]) - 1); 54 55 cout<<"test"<<endl; 56 for(int i=0;i<7;i++) 57 cout<<a[i]<<" "; 58 }
执行程序会发现在算法排序的地方无限循环,想了半天才知道是33和41行的位置,不管while循环是否执行都会执行swap语句。逻辑错误!
只能换种方法,改成大家最常见的那种就好了
1 void quick_sort(int a[],int low,int high) 2 { 3 4 if(low>=high) 5 return; 6 7 int first; 8 int last; 9 first=low; 10 last=high; 11 12 int x; 13 x=a[low]; 14 15 16 while(low<high) 17 { 18 while(low<high&&a[high]>=x) 19 { 20 high--; 21 } 22 a[low]=a[high]; 23 24 // cout<<i<<" "<<low<<" low"<<" "<<high<<endl; 25 26 while(low<high&&a[low]<=x) 27 { 28 low++; 29 } 30 a[high]=a[low]; 31 // swap(a[high],a[low]); 32 // cout<<i<<" "<<low<<" high"<<" "<<high<<endl; 33 } 34 a[low]=x; 35 36 if(first<low-1) 37 quick_sort(a,first,low-1); 38 if(last>low+1) 39 quick_sort(a,low+1,last); 40 }
这里就不是交换了,直接赋值,然后最后给a[low]赋值。
很低级的错误