64,654
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
using namespace std;
int Partition(int a[],int low,int high){
int pivot=a[low];//第0个位置记录枢轴值
while (low < high)
{
while (low<high && pivot<a[high])
{
--high; //将比枢轴小的记录移到低端
}
a[low]=a[high];
low++;
while (low<high &&pivot>a[low])
{
low++;
}
a[high]=a[low];
high--;
}
if(low>=high)
{
a[low]=pivot;
cout<<"返回的low值是"<<low<<endl;
for(int i=0;i<low;i++){
cout<<a[i]<<" ";}
cout<<'\n';
return low;
}
else
{
a[high]=pivot;
cout<<high<<endl;;
return high;
}
}
void QuickSort(int a[],int low,int high)
{
int pivotLocation;//记录枢轴位置
if (low<high)//保证区间长度大于1
{
pivotLocation=Partition(a,low,high);//划分区间,并得到枢轴位置
QuickSort(a,low,pivotLocation-1);//对枢轴左区间进行快排
QuickSort(a,pivotLocation+1,high);//对枢轴右区间进行快排
}
}
int main()
{
int b[10]={6,7,4,1,52,33,2,1,4,1};
Partition(b,0,9);
for(int i=0;i<10;i++){
cout<<b[i]<<" ";
}
cout<<endl;
QuickSort(b,0,9);
for(int i=0;i<10;i++){
cout<<b[i]<<" ";
}
return 0;
}
#include<iostream>
using namespace std;
int Partition(int a[],int low,int high){
int pivot=a[low];//第0个位置记录枢轴值
while (low < high)
{
while (low<high && pivot<a[high])
{
--high; //将比枢轴小的记录移到低端
}
if(low<high) a[low++]=a[high];//这里要加 low<high条件 因为可能有low==high的情况出现
while (low<high &&pivot>=a[low])
{
low++;
}
if(low<high) a[high--]=a[low];
}
if(low>=high)
{
a[low]=pivot;
// cout<<"返回的low值是"<<low<<endl;
// for(int i=0;i<low;i++){
// cout<<a[i]<<" ";}
// cout<<'\n';
return low;
}
else
{
a[high]=pivot;
// cout<<high<<endl;;
return high;
}
}
void QuickSort(int a[],int low,int high)
{
int pivotLocation;//记录枢轴位置
if (low<high)//保证区间长度大于1
{
pivotLocation=Partition(a,low,high);//划分区间,并得到枢轴位置
QuickSort(a,low,pivotLocation-1);//对枢轴左区间进行快排
QuickSort(a,pivotLocation+1,high);//对枢轴右区间进行快排
}
}
int main()
{
int b[10]={6,7,4,1,52,33,2,1,4,1};
Partition(b,0,9);
for(int i=0;i<10;i++){
cout<<b[i]<<" ";
}
cout<<endl;
QuickSort(b,0,9);
for(int i=0;i<10;i++){
cout<<b[i]<<" ";
}
return 0;
}