算法之路——快速排序

  前面讨论的是通过插入来排序的。这篇是关于通过交换来排序的,最简单的就是冒泡排序。另一种利用交换来排序的就是快速排序。快速排序是对冒泡排序的一种改进。基本思想是:通过一趟排序将待排序记录分割成独立的两个部分,其中一部分记录的关键字均比另一组关键字小,再分别对这两部分记录继续进行排序,以达到整个序列有序。

以下是该算法的代码实现:

/*这是quick_sort.h文件*/
#ifndef quick_sort
#define quick_sort

#define MAXSIZE 100
typedef int KeyType;

typedef struct {
KeyType data;
//其他的属性
}RedType,* PRedType;

typedef struct {
RedType list[MAXSIZE];
int length;
}SqList, * PSqList;

#define K_T "%d" //用于输入输出 如 printf(K_T, p->list[i].data);

#define OK 0
#define P_NULL 1
#define TOOBIG 2
#define NUM_ERROR 3

int comp(void * d1, void * d2);
int inputList (PSqList p,int length);
int outputList (PSqList p);
int quickSort (PSqList p, int (*comp)(void *, void *));

#endif


/*这是quick_sort.cpp文件*/
#include "quick_sort.h"
#include <stdio.h>
int inputList (PSqList p,int length)
{//输入序列

if (p == NULL)
return P_NULL; //1,指针是空的
if (length > MAXSIZE)
return TOOBIG; //2,要输入的序列太多

int i = 0;
for (i = 0; i < length; i++)
if (scanf(K_T,&(p->list[i].data)) != 1)
return NUM_ERROR; //3,输入的数字有误

p->length = length;
return OK; //0
}

int outputList (PSqList p)
{//输出序列
if (p == NULL)
return P_NULL;

int i = 0;
for (i =0; i < p->length; i++)
printf (K_T"\t",p->list[i].data);
putchar('\n');
return OK;
}//outputList


static int partition (PSqList p, int (*comp) (void *, void *), int low, int high)
{//交换顺序表[low...high]记录,枢轴记录到位,并返回其值,此时在它之前的记录不大于它,在它之后的记录不小于它

RedType tmp = p->list[low]; //用于存储中轴

while (low < high)
{
while (low < high && comp (&(p->list[high]), &(tmp)) >= 0)
high--;
p->list[low] = p->list[high];

while (low < high && comp (&(p->list[low]), &(tmp)) <= 0)
low++;
p->list[high] = p->list[low];
}
p->list[low] = tmp;

return low;
}//partition

static int QSort (PSqList p, int (*comp)(void *, void *),int low, int high)
{//对顺序表p的子序列list[low,high]进行排序
if (low >= high)
return 0;

int pivotloc = 0;
pivotloc = partition(p,comp, low, high);
QSort (p, comp, low, pivotloc - 1);
QSort (p, comp, pivotloc +1, high);
return OK;
}//QSort

int quickSort (PSqList p, int (*comp)(void *, void *))
{//对表p进行快速排序
QSort (p,comp,0,p->length-1);
return OK;
}//quickSort


/*这是main.cpp文件*/
#include <stdio.h>
#include <stdlib.h>
#include "quick_sort.h"

int comp(void * d1, void * d2);

int main (int argc, char * argv)
{
int status;
PSqList test;
test = (PSqList)malloc(sizeof(SqList));
int n = 0 ;
printf("请输入第一组待排序的数的个数(输入0结束循环):");

while (1)
{
while (scanf("%d",&n) != 1)
{
puts("输入有误!请重新输入!");
while(getchar() != '\n');
}

if (n == 0) //结束
break;
if (status = inputList(test, n) != 0)
{
puts("输入的数字有误!");
while(getchar() != '\n');
//exit(status);
}
quickSort(test,comp);
outputList(test);
printf("请输入下一组待排序的数的个数(输入0结束循环):");
}
free(test);
return 0;
}


int comp(void * d1, void * d2)
{//比较函数
return (((PRedType)d1)->data - ((PRedType)d2)->data );
}



原文地址:https://www.cnblogs.com/svking/p/quickSort.html