排序算法(2)

排序算法(2)

希尔排序

希尔(Shell)排序又称为缩小增量排序,它是一种插入排序。它是直接插入排序算法的一种威力加强版。该方法因DL.Shell于1959年提出而得名。

#include<iostream>
using namespace std;

int a[10] = { 9,8,7,6,5,4,3,2,1,0 };

void shell_sort(int size)
{
	int gap = size >> 1;
	int i, key, end;
	while (gap > 0)
	{
		for (i = gap; i < size; i++)
		{
			key = a[i];
			end = i - gap;
			while (end >= 0 && key < a[end])
			{
				a[end + gap] = a[end];
				end -= gap;
			}
			a[end + gap] = key;
		}
		gap >>= 1;
	}
}

int main()
{
	shell_sort(10);

	for (int i = 0; i < 10; i++)
	{
		cout << a[i] << ' ';
	}
	cout << endl;


	system("pause");
	return 0;
}

选择排序

算法描述:在未排序的序列中找到最小的元素,存放到序列的首位置,找到最大的元素存放到序列的末尾.然后抛开首位和末尾,继续重复该步骤,直到排完为止.

#include<iostream>
using namespace std;

int a[10] = { 9,8,7,6,5,4,3,2,1,0 };

void selection_sort(int size)
{
	int left = 0;
	int right = size - 1;
	int i;

	while (left < right)
	{
		int MAX = right;
		int MIN = left;

		for (i = left; i <= right; i++)
		{
			if (a[MAX] < a[i])
				MAX = i;
			if (a[MIN] > a[i])
				MIN = i;
		}

		int temp = a[MAX];
		a[MAX] = a[right];
		a[right] = temp;

		if (MIN == right)
			MIN = MAX;

		temp = a[MIN];
		a[MIN] = a[left];
		a[left] = temp;

		left++;
		right--;
	}


}

int main()
{
	selection_sort(10);

	for (int i = 0; i < 10; i++)
	{
		cout << a[i] << ' ';
	}
	cout << endl;


	system("pause");
	return 0;
}

堆排序

运用了二叉树思想

算法描述:若升序的话,就将堆调成一个大堆,若降序的话,就将堆调成一个小堆.从倒数第一个非叶子节点开始往根遍历,若当前节点的值都大于左右孩子,则不用动,若是小于,就将左右孩子当中最大的节点与当前节点交换,交换后就需要进行向下调整(因为交换会影响大堆结构).重复上述步骤,直到根节点为止.

#include<iostream>
using namespace std;

int a[10] = { 9,8,7,6,5,4,3,2,1,0 };

void HeapAdjust(int size, int parent)
{
	int child = parent * 2 + 1;
	while (child < size)
	{
		if (child + 1 < size&&a[child + 1] > a[child])
			child++;
		if (a[child] > a[parent])
		{
			int temp = a[child];
			a[child] = a[parent];
			a[parent] = temp;

			parent = child;
			child = parent * 2 + 1;
		}
		else
			return;
	}

}

void HeapSort(int size)
{
	int root = (size - 2) >> 1;
	int end = size - 1;

	for (; root >= 0; root--)
	{
		HeapAdjust(size, root);
	}

	while (end)
	{
		int temp = a[0];
		a[0] = a[end];
		a[end] = temp;

		HeapAdjust(end, 0);
		end--;
	}
}

int main()
{
	HeapSort(10);

	for (int i = 0; i < 10; i++)
	{
		cout << a[i] << ' ';
	}
	cout << endl;


	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值