快速排序算法初步描述如下:
(1)if(A[i] ~ A[j] 至少包含两个不同的关键字)
(2)令v的值为分块中最左两个不同关键字的较大值
(3)对A[i],……A[j]中的元素进行置换:
在i+1到j中确定一个k,使A[i],……A[k-1]的关键字都小于v,
A[k],……A[j]的关键字都不小于v;
(4)QuickSort(i, k-1);
(5)QuickSort(k, j);
快速排序比较法
#include <iostream>
#define maxsize 100
using namespace std;
typedef int keytype;
typedef int fields;
struct records
{
keytype key;
fields others;
} ;
typedef records LIST[maxsize];
int FindPivot(int i,int j,LIST A)
{
/*
如果A[i],…,A[j]的关键字全部相同,则返回0;
否则,返回左边两个不同关键字中较大者的下标
*/
keytype firstkey;
int k;
firstkey = A[i].key;
for( k=i+1; k<=j; k++)
{
if(A[k].key > firstkey)
return k;
else if(A[k].key < firstkey)
return i;
}
return 0;
}//FindPivot
void Swap(records *x,records *y)//交换元素
{
/*records temp;
temp = x;
x = y;
y = temp;*/
int t1,t2;
t1=x->key;
t2=x->others;
x->key=y->key;
x->others=y->others;
y->key=t1;
y->others=t2;
}
int Partition(int i,int j,keytype pivot,LIST A)
{
/*
划分A[i],…,A[j],使关键字小于pivot的在左子序列,关键字不小于
pivot的在右子序列;返回右子序列的开头下标
*/
int l,r;
l = i;
r = j;
do{
Swap(&A[l],&A[r]);
while(A[l].key < pivot)
l = l + 1;
while(A[r].key >= pivot)
r = r - 1;
} while(l <= r);
return l;
}
void QuickSort(int i,int j,LIST A,int amount)
{
keytype pivot;//基准元素
int pivotindex;
int k;
int m;
pivotindex = FindPivot(i,j,A);
if(pivotindex != 0)
{
pivot = A[ pivotindex ].key;
k = Partition(i,j,pivot,A);
for(m=1;m<=amount;m++)
cout << A[m].key << " ";
cout << endl;
QuickSort(i,k-1,A,amount);
QuickSort(k,j,A,amount);
}
}//QuickSort
int main()
{
LIST A;
A[0].key = -1;
int n,i;
int amount;
cout << "数据个数n:" << endl;
cin >> n;
amount = n;
cout << "依次输入n个数据:" << endl;
for(i=1;i<=n;i++)
cin >> A[i].key;
QuickSort(1,n,A,amount);
cout << "排序后的n个数据:" << endl;
for(i=1;i<=n;i++)
cout << A[i].key << " ";
cout << endl;
return 0;
}
快速排序中值法
#include <iostream>
#define maxsize 100
using namespace std;
typedef int keytype;
typedef int fields;
struct records
{
keytype key;
fields other;
} ;
typedef records LIST[maxsize];
void QuickSort_M(LIST L,int left,int right)
{
if(left >= right)
return ;
int i,j;
records x,temp;
x = L[left];
i = left;
j = right;
while(i<=j)
{
while((i<=j)&&(L[i].key<x.key))
i++;
while((i<=j)&&(L[j].key>x.key))
j--;
if(i<=j)
{
temp = L[i];
L[i] = L[j];
L[j] = temp;
++i;
--j;
}
}
QuickSort_M(L,left,j);
QuickSort_M(L,i,right);
}
int main()
{
LIST A;
int n,i;
cout << "数据个数:" << endl;
cin >> n;
for(i=1;i<=n;i++)
cin >> A[i].key;
QuickSort_M(A,1,n);
for(i=1;i<=n;i++)
cout << A[i].key << " ";
return 0;
}