快速排序Qsort看了好久都没看懂,直到看到白话的挖坑填数才恍然大悟
记录结构:
typedef int KeyType;
typedef struct
{
KeyType key;
//others key
}RcdType;
typedef struct
{
RcdType *rcd;
int length;
int size;
}RcdList;
核心代码:
int Partition(RcdType rcd[], int low, int high)
{
while (low < high) {
rcd[0] = rcd[low]; //low挖坑
while (high > low && rcd[0].key <= rcd[high].key) high--;
rcd[low] = rcd[high]; //high挖来补low坑
while (high > low && rcd[0].key >= rcd[low].key) low++;
rcd[high] = rcd[low]; //low挖来补high坑
}
rcd[low] = rcd[0]; //最后的坑补上,rcd[high] = rcd[0];其实也一样
return low;
}
void QSort(RcdType rcd[], int s, int t)
{
if (s < t) {
int pivotloc; //枢轴
pivotloc = Partition(rcd, s, t);
QSort(rcd, s, pivotloc - 1);
QSort(rcd, pivotloc + 1, t);
}
}
#include <stdlib.h>
#include <stdio.h>
#include "structure_data.h"
#include "qsort.h"
void InitRcdList(RcdList &L, KeyType key[], int n)
{
L.length = n;
L.size = n + 1;
L.rcd = (RcdType*)malloc(L.size * sizeof(RcdType));
for (int i = 0; i < n; i++)
L.rcd[i + 1].key = key[i];
}
void PrintListKey(RcdList L)
{
if (L.rcd == NULL) return;
for (int i = 1; i <= L.length; i++)
printf("%d ", L.rcd[i].key);
printf("\n");
}
int main()
{
RcdList list;
KeyType key[7] = { 42, 30, 68, 98, 86, 15, 57 };
InitRcdList(list, key, 7);
PrintListKey(list);
QSort(list.rcd, 1, list.length);
PrintListKey(list);
system("pause");
return 0;
}
另外,“为了避免枢轴关键字为最大或者最小的情况,可采用‘三者取中’的方法,即rcd[s],rcd[t]和rcd[(s+t)/2]三者中关键字的大小居中的数据为枢轴,并于rcd[s]互换”