思路+代码:
思路:
一开始调用quicksort(a , 0, a.length-1)
quicksort(a, p, r)
if p < r
q = partition(a, p, r)
quicksort(a, p, q-1)
quicksort(a, q+1, r)
partition(a, p, r)
x = a[r]
i = p - 1
for j = p to r - 1
if a[j] < x
i = i + 1
exchange a[i] with a[j]
exchange a[i + 1] with a[r]
return i + 1
代码:
#define _CRT_SECURE_NO_WARNINGS
#include<vector>
#include<iostream>
#include<math.h>
#include<string>
using namespace std;
int patition(int a[],int p, int r){
int temp;
int i = p - 1;
for (int j = p; j < r; j++)
if (a[j] < a[r])
{i = i + 1; temp = a[i]; a[i] = a[j]; a[j] = temp;}
temp = a[i + 1]; a[i+1] = a[r]; a[r] = temp;
return i + 1;
}
void quicksort(int a[],int p, int r){
if (p < r){
int q = patition(a, p, r);
quicksort(a,p, q - 1);
quicksort(a,q + 1, r);
}
}
int main(){
int a[8] = { 1,3,2,30,69,4,7,100 };
quicksort(a, 0, 7);
for (int i = 0; i < 8; i++)
cout << a[i]<<" ";
cout << endl;
}