快速排序算法是基于分治策略的另一个排序算法。其基本思想是,对于输入的子数组,按以下三步进行排序。
一:分解
二:递归求解
三:合并
版本一:
#include <stdio.h>
#include <string.h>
#define SWAP(x,y){int t;t=x;x=y;y=t;}
int Partition(int a[], int left, int right)
{
int x, i, j;
x = a[right];
i = left - 1;
for(j = left; j <= right-1; j++)
{
if(a[j] <= x){
i++;
SWAP(a[i], a[j]);
}
}
SWAP(a[i+1], a[right]);
return i+1;
}
void QuickSort(int a[], int left, int right)
{
int q;
if(left < right)
{
q = Partition(a, left, right);
QuickSort(a, left, q-1);
QuickSort(a, q+1, right);
}
}
int main()
{
int a[]={2,8,7,1,3,5,6,4}, i;
QuickSort(a, 0, 7);
for(i = 0; i <= 7; i++)
{
printf("%d ", a[i]);
}
system("pause");
}
版本二:
#include <stdio.h>
#include <time.h>
#define SWAP(x,y){int t; t =x; x = y; y = t;}
#define random(x) (rand()%x)
int Partition(int a[], int left, int right)
{
int i, x, j;
x = a[right];
i = left-1;
for(j = left; j <= right-1; j++)
if(a[j] <= x)
{
i++;
SWAP(a[i], a[j]);
}
SWAP(a[i+1], a[right]);
return i+1;
}
int Partiton_random(int a[], int left , int right)
{
int i = random(right);
i = (i+left)>right?i:left+i;
SWAP(a[i],a[right]);
return Partition(a, left, right);
}
void QuickSort_random(int a[], int left, int right)
{
int q;
if(left < right)
{
q = Partiton_random(a, left, right);
QuickSort_random(a, left, q-1);
QuickSort_random(a, q+1, right);
}
}
int main()
{
int a[]={2,8,7,1,3,5,6,4}, i;
srand(time(NULL));
QuickSort_random(a, 0, 7);
for(i = 0; i <= 7; i++)
printf("%d ", a[i]);
system("pause");
return 0;
}
版本三:
#include <iostream>
#define N 8
typedef int Type;
using namespace std;
void QuickSort(Type a[], int left, int right)
{
if(left < right)
{
int i = left, j = right, key = a[left];
do{
while(i < j && a[j] >= key)
j--;
if(i < j) a[i++] = a[j];
while(i < j && a[i] < key)
i++;
if(i < j) a[j--] = a[i];
}while(i != j);
a[i] = key;
QuickSort(a, left, i-1);
QuickSort(a, i+1, right);
}
}
int main()
{
Type a[] = {2,8,7,1,3,5,6,4};
QuickSort(a, 0, 7);
for(int i = 0; i < N; i++)
cout << a[i] << ',';
cout << endl;
// int j;
// cin >> j;
return 1;
}
最原始的快排是:只介绍伪码了
HOARE-PARTITION(A, p, r)
x = A[p]
i = p-1
j = r+1
while(TRUE)
repeat
j = j-1;
until A[j] <= x
repeat
i = i+1
until A[i] >= x
if(i < j)
exchange A[i] with A[j]
else return j
快速排序,是一种原址排序算法,但最坏情况运行时间是n^2。然而它的期望运行时间是nlg(n) ,而且在实际应用中通常比堆排序要快。与插入排序类似,快速排序的代码也很紧凑,因此运行时间中隐含的常数系数很小。而且快速排序是排序大数组的最常用算法。