思路:
快排的思路就是寻找一个分界点,左边的数均小于右边的。
那么如何来找这个分界点呢?
例如a[5] = {7,8,6,5,4}
7 8 6 5 4
l = 0 ; r = 4 a[l] > a[r] swap(a[l] ,a[r]) l++
4 8 6 5 7
l = 1; r = 4 a[l] > a[r] swap(a[l] ,a[r]) l++
4 7 6 5 8
l = 2; r = 4 a[l] < a[r] r--
4 7 6 5 8
l = 2; r = 3 a[l] > a[r] swap(a[l] ,a[r]) l++
4 7 5 6 8
l = 3; r = 3
这样就将数组分成两部分a[0]-a[3] a[4]
这段代码有问题,但是暂时保留,过后改:
#include <iostream>
using namespace std;
void swap(int &a,int &b) {
int temp;
temp = a;
a = b;
b = temp;
}
int Mid(int a[],int l,int r){
if(l == r) return l;
while(l < r){
while(l < r && a[r] <= a[l]){
swap(a[l],a[r]);
l++;
}
while(l < r && a[r] > a[l]){
r--;
}
}
return l;
}
void QuickSort(int a[],int l,int r){
if(l < r){
int mid = Mid(a,l,r);
QuickSort(a,l,mid);
QuickSort(a,mid+1,r);
}
else if(l == r){
return;
}
}
int main() {
int a[5] = {5,4,3,2,1};
QuickSort(a,0,4);
for(int i = 0; i < 5; i++)
cout << a[i] << endl;
/*int a = 0, b = 1;
cout << a << ' ' << b << endl;
swap(a, b);
cout << a << ' ' << b << endl;*/
system("pause");
return 0;
}
课本代码:
#include <iostream>
#include <vector>
using namespace std;
int Mid(vector<int>& a,int low,int high){
int pivot = a[low];
while(low < high){
while(low < high && a[high] >= pivot)
high--;
a[low] = a[high];//这里一定是要先低后高,因为第一个数又被pivot存储起来,如果反过来的话,可能会出现某个值丢失
while(low < high && a[low] <= pivot)
low++;
a[high] = a[low];
}
a[low] = pivot;
return low;
}
void QuickSort(vector<int>& a,int l,int r){
if(l < r){
int mid = Mid(a,l,r);
QuickSort(a,l,mid);
QuickSort(a,mid+1,r);
}
else if(l == r){
return;
}
}
int main() {
int m[4] = {3,5,1,0};
vector<int> a(m,m+4);
QuickSort(a,0,3);
for(int i = 0; i < 4; i++)
cout << a[i] << endl;
/*int a = 0, b = 1;
cout << a << ' ' << b << endl;
swap(a, b);
cout << a << ' ' << b << endl;*/
system("pause");
return 0;
}