快排分为两种,一种是双边循环法,另一种是单边循环法。
注意: 快排里的i与j下标比较时都要使用i < j,否则算法会错误!!!
(一)双边循环法:
#include<iostream>
using namespace std;
void QuickSort(int arr[],int l,int r);
void show(int arr[],int n);
int main(){
int arr[10] = {213,42,13,53,1243,72,321,843,134,77};
QuickSort(arr,0,9);
show(arr,10);
return 0;
}
void show(int arr[],int n){
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
void QuickSort(int arr[],int l,int r){//快速排序
if(l > r)
return;
int temp = arr[l];
int i = l,j = r;
while(i != j){
while(j > i && arr[j] >= temp)//注意要判断j>i
j--;
if(i < j){//注意要判断j>i
arr[i] = arr[j];
i++;
}
while( j > i && arr[i] <= temp)//注意要判断j>i
i++;
if(i < j){//注意要判断j>i
arr[j] = arr[i];
j--;
}
}
arr[i] = temp;
QuickSort(arr,l,i-1);
QuickSort(arr,i+1,r);
}
(二)单边循环法:
void sigleLoop(int[] array, int startIndex, int endIndex) {
if(startIndex>=endIndex) {
return;
}
int partition = partitionV2(array, startIndex, endIndex);
sigleLoop(array, startIndex, partition-1);
sigleLoop(array, partition+1, endIndex);
}
int partitionV2(int[] array, int startIndex, int endIndex) {
int pivot = array[startIndex];
int mark = startIndex;
for(int i=startIndex+1; i<=endIndex; i++) {
if(array[i]<pivot) {
mark++;
int temp = array[mark];
array[mark] = array[i];
array[i] = temp;
}
}
array[startIndex] = array[mark];
array[mark] = pivot;
return mark;
}