快速排序是通过一趟排序,确定某一个元素的位置,然后将分为左右两部分,左边都比这个元素小,而右边都比这个元素大,然后左右两边继续快速排序。
快速排序是典型的的分治算法
#include"../init.h"
//一趟排序
int part(RedType *node, int low, int high){
KeyType point = node[low].key;
while(low < high){
while(low < high && node[high].key >= point){
--high;
}
exchange( &node[low], &node[high]);
while(low < high && node[low].key <= point){
++low;
}
exchange( &node[low], &node[high]);
}
return low;
}
//一趟排序的改进版本
//交换过程中对枢纽记录的赋值是多余的
int new_part(RedType *node, int low, int high){
RedType p = node[low];
KeyType point = node[low].key;
while(low < high){
while(low < high && node[high].key >= point){
--high;
}
node[low] = node[high];
while(low < high && node[low].key <= point){
++low;
}
node[high] = node[low];
}
node[low] = p;
return low;
}
//快速排序
//一趟排序后,拆分为两个子部分
void QuickSort(RedType *node, int low, int high){
if(low < high){
int mid = new_part(node,low,high);
QuickSort(node,low,mid-1);
QuickSort(node,mid+1,high);
}
}
int main(){
Sqlist L;
init(&L);
QuickSort(L.r,1,L.length);
show(L.r);
return 0;
}