快速排序

快速排序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]互换”


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值