选择排序
基本思想
每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完 。
而在这里我进行了稍微的优化,就是选择最小的放在起始位置,最大的放在最末位置,图解一下就很清楚了。
图解
时间和空间复杂度
时间复杂度是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;
}