快速排序详细讲解(C与C++)
例如一串数字8 5 7 22 11 3 9 ,如图所示:
low指向8,high指向9。让temp=8(将第一个数字赋值给temp)。然后从后往前遍历寻找比temp小的数字,第一个数字是9比temp大,则继续向前遍历,第二个数字3比temp小,这时候将3赋值给low指向的数字。如图所示:
相同的从前向后遍历寻找比temp大的数字,直到low指向22(也就是low=3时),将22赋值给high此时指向的数字。如图所示:
继续交替,从后往前遍历寻找比temp小的数字,直到low=high时,将temp赋值给low或者high指向的数字,如图所示:
第一次完成结果为3 5 7 8 11 22 9,接下来将这一段数字从low指向的地方分开分为3 5 7和11 22 9,然后继续上面的操作不断重复就排序好了。
C++代码
#include<iostream>
using namespace std;
class Quick{
private:
int low,high;
int *p;//存放数组
int length;//记录数组长度
public:
Quick(int *s,int l);
~Quick();
void quick_sort(int l,int h);//循环迭代
int Index(int l,int h);//获取最终的low
void print();//输出最终结果
};
Quick::Quick(int *s,int l)
{
length=l;
p=new int[length];
for(int i=0;i<length;i++)
p[i]=s[i];
}
void Quick::quick_sort(int l,int h)
{
if(l<h)
{
int dex=Index(l,h);
quick_sort(0,dex-1);
quick_sort(dex+1,h);
}
}
int Quick::Index(int l,int h)
{
low=l;
high=h;
int temp=p[low];
while(low<high)
{
while((p[high]>temp || p[high]==temp)&& low<high)
high--;
p[low]=p[high];
while((p[low]<temp || p[low]==temp)&& low<high)
low++;
p[high]=p[low];
if(low==high)
p[low]=temp;
}
return low;
}
void Quick::print()
{
cout<<"排序后的结果为"<<endl;
for(int i=0;i<length;i++)
cout<<p[i]<<" ";
cout<<endl;
}
Quick::~Quick()
{
if(p)
{
delete []p;
cout<<"p释放成功"<<endl;
}
}
int main()
{
int a[100];//创建一个空间足够大的数组
cout<<"请输入你想排序的一串数字,以-1结束"<<endl;
for(int i=0;a[i-1]!=-1;i++)
cin>>a[i];
Quick qs(a,i-1);
qs.quick_sort(0,i-2);
qs.print();
return 0;
}
结果:
C语言代码
#include<stdio.h>
#include<stdlib.h>
void main()
{
int Index(int *a,int low,int high);//定义Index函数
void quick_sort(int *a,int low,int high);//定义quick_sort函数
void print(int *a);//定义print函数
printf("请输入任意顺序的是个整数\n");
int p[10];
for(int i=0;i<10;i++)
scanf("%d",&p[i]);
Index(p,0,10-1);//调用Index 函数
quick_sort(p,0,10-1);//调用quick_sort函数
print(p);//调用print函数
}
int Index(int *a,int low,int high)//获取low
{
int temp=a[low];
while(low<high)
{
while((a[high]>temp || a[high]==temp)&& low<high)
high--;
a[low]=a[high];
while((a[low]<temp || a[low]==temp)&& low<high)
low++;
a[high]=a[low];
if(low==high)
a[low]=temp;
}
return low;
}
void quick_sort(int *a,int low,int high)
{
if(low<high)
{
int dex=Index(a,low,high);
quick_sort(a,0,dex-1);
quick_sort(a,dex+1,high);
}
}
void print(int *a)
{
printf("排序后的结果为:\n");
for(int i=0;i<10;i++)
printf("%d ",a[i]);
printf("\n");
}
结果:
以上就是我对快速排序所解释的所有内容,谢谢观看。