【趣学算法】--快速排序

这篇博客介绍了如何使用C语言实现快速排序算法,包括Partition函数的两种实现方式Partition和Partition2,以及相应的QuickSort主排序函数。代码示例展示了输入数据、排序过程及输出排序结果。
摘要由CSDN通过智能技术生成

快速排序

代码来源–趣学算法第3章

#define _CRT_SECURE_NO_WARNINGS  1

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<stdbool.h>
#include<algorithm>
using namespace std;


int Partition(int r[], int low, int high)
{
	int i = low;
	int j = high;
	int pivot = r[low];

	while (i < j)
	{
		while (i<j && r[j] >pivot)
			j--;
		if (i < j)
		{
			swap(r[i++], r[j]);
		}
		while (i < j && r[i] <= pivot)
			i++;
		if (i < j)
		{
			swap(r[i], r[j--]);
		}
	}
	return i;
}

int Partion2(int r[], int low, int high)
{
	int i = low, j = high, pivot = r[low];
	while (i < j)
	{
		while (i<j && r[j]>pivot)
			j--;
		while (i < j && r[i] <= pivot)
			i++;
		if (i < j)
		{
			swap(r[i++], r[j--]);
		}
	}

	if (r[i] > pivot)
	{
		swap(r[i - 1].r[low]);
		return i - 1;
	}
	swap(r[i], r[low]);
	return i;
}

void QuickSort(int R[], int low, int high)
{
	int mid;
	if (low < high)
	{
		mid = Partition(R, low, high);
		QuickSort(R, low, mid - 1); 
		QuickSort(R, mid + 1, high);

	}
}

int main()
{
	int a[1000];
	int i, n;
	printf("请输入要排序的数据的个数:\n");
	scanf("%d", &n);
	printf("请输入要排序的数据;\n");
	for (i = 0; i < n; i++)
		scanf("%d", &a[i]);
	printf("\n");
	QuickSort(a, 0, n - 1);
	printf("排序后的序列为:\n");
	for (i = 0; i < n; i++)
		printf("%d ", a[i]);
	printf("\n");



	return 0;
}

后记

这里是用c写的,其实都差不多。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值