数据结构第六天(快速排序)

目录

前言

概述

源码:

主函数:

运行结果:


前言

最好的期待是未来可期,
最好的相遇是开学有你。

想开学啦!!!

概述

快速排序 Quick Sort 的基本思想是:通过 一趟排序将待排记录分割成独立的 两部分,

其中一部分记录的关键字均比另 部分记录的关键字小,

则可分别对这两部 分记录继续进行排序,以达到整个序列有序的目的。

废话不多说,接下来解释一下这个算法主要部分。

生成如下随机整数:

544  118  686  950  743  456  963  642  374  149  741  250  177  969  591  98;

我们需要做的第一步,就是先选取当中的一个关键字,比如选择第一个关键字 544,

然后想尽办法将它放到一个位置,使得它左边的值都比它小,右边的值都比它大,

第一次排序后:

98  118  177  250  149  456  374  544  642  963  741  743  950  969  591  686;

从上面结果可以看出,关键字 544左边的值都比其小,544右边的值都比其大。

544左边的值:98  118  177  250  149  456  374;

544右边的值: 642  963  741  743  950  969  591  686;

以上两个新的队列,又可以执行第一步。

我们可以很容易想到,这儿可以使用递归。

说到这儿,快速排序的思想基本就结束了,以下是个人在学习过程中实现的代码。

源码:

int*  partition(int* ptr,int* low, int* high)
{
	*ptr = *low;
	while (true)
	{
		while (high != low)
		{
			if (*high < *ptr)
			{
				*low = *high;
				break;
			}
			--high;
		}
		while (high != low)
		{
			if (*low>*ptr)
			{
				*high = *low;
				break;
			}
			++low;
		}
		if (high == low)
		{
			*low = *ptr;
			break;
		}
	}
	return low;
}
void Qsort(int* ptr, int* low, int* high)
{
	if (low < high)
	{
		int*pivotloc = partition(ptr, low, high);
		Qsort(ptr, low, pivotloc - 1);
		Qsort(ptr, pivotloc + 1,high );
	}

}
void sortByQuickSort(int* dest, const unsigned int dataCnt)
{
	int* ptr = (int*)calloc(sizeof(int), dataCnt + 1);
	memcpy_s(ptr + 1, sizeof(int)*dataCnt, dest, sizeof(int)*dataCnt);
	int* low = ptr + 1;
	int* high = ptr + dataCnt;
	Qsort(ptr, low, high);
	

	memcpy_s(dest, sizeof(int)*dataCnt, ptr + 1, sizeof(int)*dataCnt);
}

主函数:

#include<stdio.h>
#include<iostream>
using namespace std;
#include"dataStructAPI.h"
#include"sort.h"
#include<windows.h>
int main()
{

	int array[16] = { 0 };
	numberProducer.getFilledArray(array,16);
	cout << "  原 始 数 据   :";
	numberProducer.showArray(array,16);

	sortByQuickSort(array, 16);
	cout << "快 速 排 序 后  :";
	numberProducer.showArray(array, 16);

	sortByBubbleSort(array, 16);
	cout << "冒 泡 排 序 后  :";
	numberProducer.showArray(array, 16);

	sortByShellInsert(array, 16, 3);
	cout << "希尔插入排序后  :";
	numberProducer.showArray(array, 16);

	sortByBinarySearchInsert(array, 16);
	cout << "折半插入排序后  :";
	numberProducer.showArray(array, 16);

	sortByDirectInsert(array, 16);
	cout << "直接插入排序后  :";
	numberProducer.showArray(array, 16);
	system("pause");
	return 0;
}

运行结果:

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值