程序员成长之旅——选择排序

选择排序

基本思想

每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完 。

而在这里我进行了稍微的优化,就是选择最小的放在起始位置,最大的放在最末位置,图解一下就很清楚了。
图解
在这里插入图片描述

时间和空间复杂度

时间复杂度是O(n^2)
空间复杂度是O(1)

稳定性

不稳定

代码实现
#include<iostream>
#include<algorithm>
using namespace std;
//选择排序
//时间复杂度是O(N*N)
void SelectSort(int *a, int n)
{
	int min_index = 0;
	int max_index = 0;
	int left = 0;
	int right = n - 1;
	while (left < right)
	{
		for (int i = left; i <= right; ++i)
		{
			if (a[i] < a[min_index])
				min_index = i;
			if (a[i] > a[max_index])
				max_index = i;
		}

		swap(a[left], a[min_index]);
		//一定要注意这个最大值有可能被调换走
		if (left == max_index)
			max_index = min_index;
		swap(a[right], a[max_index]);

		++left;
		--right;

		min_index = left;
		max_index = right;
	}
}
void PrintSort(int *a,int n)
{
	for (int i = 0; i < n; ++i)
	{
		cout << a[i] << " ";
	}
	cout << endl;
}
int main()
{
	int array[10] = { 9,1,2,5,4,3,6,7,8,0 };
	int size = sizeof(array) / sizeof(int);
	SelectSort(array, size);
	PrintSort(array, size);
	return 0;
}

堆排序

基本思想

升序我们都是建大堆,降序我们是建小堆

图解
在这里插入图片描述
在这里插入图片描述

先建好大堆之后,将根和尾元素进行交换,交换完之后,在进行一次向下调整,交换尾原素的上一个,以此类推,到最后交换的再剩一个元素结束,这时候就排序好了。

时间和空间复杂度

时间复杂度是:O(N*logN)
空间复杂度是:O(1)

稳定性

不稳定

代码实现
#include<iostream>
#include<algorithm>
using namespace std;
void AdjustDown(int* a,int n,int root)
{
	int parent = root;
	int child = parent * 2 + 1;
	while(child < n)
	{
		if (child + 1 < n)
		{
			if (a[child] < a[child + 1])
				swap(a[child], a[child + 1]);
		}
		if (a[child] > a[parent])
		{
			swap(a[child], a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}
//堆排序
void HeapSort(int *a, int n)
{
	//建大堆
	for (int i = (n-2)/2; i >= 0; --i)
	{
		AdjustDown(a, n, i);
	}
	//排序
	int end = n - 1;
	while(end > 0)
	{
		swap(a[0], a[end]);
		AdjustDown(a, end, 0);
		--end;
	}
}

void PrintSort(int *a,int n)
{
	for (int i = 0; i < n; ++i)
	{
		cout << a[i] << " ";
	}
	cout << endl;
}
int main()
{
	int array[10] = { 9,1,2,5,4,3,6,7,8,0 };
	int size = sizeof(array) / sizeof(int);
	HeapSort(array, size);
	PrintSort(array, size);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

从零出发——

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值