sort.cpp

#include <string>
#include <algorithm>
#include <time.h>

using namespace std;

// 冒泡排序
void BubbleSort(int a[], int len)
{
	if (a == NULL || len <= 0)
		return;

	bool swapped;
	int last = len - 1;
	do
	{
		swapped = false;
		for (int i = 1; i <= last; i++)
		{
			// 稳定性体现在这里
			if (a[i - 1] > a[i])
			{
				int tmp = a[i - 1];
				a[i - 1] = a[i];
				a[i] = tmp;
				swapped = true;
			}
		}
		last--;	// 每一趟后减少一个带排序个数
	} while (swapped);
}

// 快排
int partition(int a[], int start, int end)
{
	if (start == end)
		return start;

	srand((unsigned int)time(NULL));

	// 在[start,end]随机选择中枢
	int pivotIndex = (rand() % (end - start + 1)) + start;
	
	// a[start]存放中枢
	Swap(&a[pivotIndex], &a[start]);
	int storeIndex = start + 1;

	for (int i = start + 1; i <= end; i++)
	{
		if (a[i] < a[start])
		{
			if (i != storeIndex)
				Swap(&a[storeIndex], &a[i]);
			storeIndex++;
		}
	}
	storeIndex--;
	Swap(&a[start], &a[storeIndex]);

	return storeIndex;
}

void QuickSort(int a[], int len)
{
	if (a == NULL || len <= 0)
		return;

	int pivotIndex = partition(a, 0, len - 1);
	if (pivotIndex > 0)
		QuickSort(a, pivotIndex);
	if (pivotIndex < len - 1)
		QuickSort(a + pivotIndex + 1, len - pivotIndex - 1);
}

// 归并排序
void Merge(int a[], int tmp[], int start, int mid, int end)
{
	int p1 = start;
	int p2 = mid + 1;
	int p = start;

	while (p1 <= mid && p2 <= end)
	{
		// 归并排序的稳定性体现在这里
		if (a[p1] <= a[p2])
			tmp[p++] = a[p1++];
		else
			tmp[p++] = a[p2++];
	}
	while (p1 <= mid)
		tmp[p++] = a[p1++];
	while (p2 <= end)
		tmp[p++] = a[p2++];

	for (int i = start; i <= end; i++)
		a[i] = tmp[i];
}

void MergeSortCore(int a[], int tmp[], int start, int end)
{
	if (start == end)
		return;

	int mid = (start + end) / 2;
	MergeSortCore(a, tmp, start, mid);
	MergeSortCore(a, tmp, mid + 1, end);
	Merge(a, tmp, start, mid, end);
}

void MergeSort(int a[], int len)
{
	if (a == NULL || len <= 0)
		return;
	
	int *tmp = new int[len];

	MergeSortCore(a, tmp, 0, len - 1);

	delete[] tmp;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值