今天又重新写了一次快排,发现之前写的有问题
#include <iostream>
using namespace std;
static int count=0;
int find(int arr[],int left,int right)
{
int i=left,j=right-1;
int temp=i;
int t=arr[temp];
while(i<=j)
{
while(i<=j&&arr[j]>=t)
{
j--;
}
if(i<=j&&arr[j]<t)
{
arr[temp]=arr[j];
arr[j]=t;
temp=j;
j--;
}
while(i<=j&&arr[i]<=t)
{
i++;
}
if(i<=j&&arr[i]>t)
{
arr[temp]=arr[i];
arr[i]=t;
temp=i;
i++;
}
}
count++;
cout<<count<<":";
for(int i=left;i<right;i++)
cout<<arr[i]<<" ";
cout<<endl;
return temp;
}
void quickSort(int arr[],int left,int right)
{
if(left>=right)
return;
int temp=find(arr,left,right);
quickSort(arr,left,temp);
quickSort(arr,temp+1,right);
}
int main()
{
int arr[]={3,-1,45,0,21,9,8,7,32};
cout<<"before sort:"<<endl;
for(int i=0;i<9;i++)
cout<<arr[i]<<" ";
cout<<endl;
quickSort(arr,0,9);
cout<<
cout<<"after sort:"<<endl;
for(int i=0;i<9;i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}
这个应该没问题,在确定一个分界数时一定是while(i<=j),不然会出错。