标签:ret 等于 turn 编写 技术 一个 wap inf sort
快速排序其实是使用分治法的思想,即在原数组中找一个数p,然后将原数组中比数p大的数放到此数的右边,比数p小的数放到次数的左边。
口诀:1.找中轴 2.左边快排 3.右边快排
主体代码如下:
void quick_sort(int * data,int left,int right){
if(left < right){
int* index = partition(data,left,right);
quick_sort(data,left,index[0]-1);
quick_sort(data,index[1]+1,right);
}
}
快速排序中,最重要的是分区partition函数的编写,有三种实现方法:
1.单向扫描分区法
代码如下:
int partition(int * data,int left,int right){
int piovet = left,scanner = left+1,bigger = right;
while(scanner <= bigger){
if(data[scanner] <= data[piovet])
scanner++;
else{
swap(data,bigger,scanner);
bigger--;
}
}
swap(data,bigger,piovet);
return bigger;
}
2.双向扫描分区方法
双向扫描的思路是,头尾指针往中间扫描,从左找到大于主元的元素,从右找到小于等于主元的元素,二者交换,继续扫描,直到左侧无大元素,右侧无小元素。
代码如下:
int partition(int * data,int left,int right){
int piovet = left,smaller = left+1,bigger = right;
while(bigger >= smaller){
while(data[smaller] <= data[piovet]&& smaller <= bigger) smaller++;
while(data[bigger] > data[piovet] && smaller <= bigger) bigger--;
if(smaller < bigger){
swap(data,smaller,bigger);
}
}
swap(data,bigger,piovet);
return bigger;
}
3.三指针分区法--有相同元素时,可以提升效率
代码如下:
int* partition(int * data,int left,int right){
int val[2] = {0};
int equal = left,scanner = left+1,bigger = right;
while(bigger >= scanner){
if(data[scanner] < data[equal]){
swap(data,scanner,equal);
scanner++;
equal++;
}else if(data[scanner] == data[equal]){
scanner++;
}else{
swap(data,scanner,bigger);
bigger--;
}
}
val[0] = equal;
val[1] = bigger;
return val;
}
标签:ret 等于 turn 编写 技术 一个 wap inf sort
原文地址:https://www.cnblogs.com/Alice-Fourier/p/12364855.html