Growth programmer trip - Selection Sort
Selection Sort
The basic idea
Each data element to be selected from the sorted minimum (or maximum) of an element stored in the starting position of the sequence, until all the data elements to be sorted drained.
And here I was a little optimization, is to choose the smallest in the starting position, the largest in the last position, graphical look very clear.
Diagram
Time and space complexity
Time complexity is O (n ^ 2)
space complexity is O (1)
stability
Unstable
Code
#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;
}
Heapsort
The basic idea
We are all built piles in ascending, descending we are to build a small heap
Diagram
After the first built on piles, the switching elements and the tail root, after the completion of the exchange, during a downward adjustment, the end of the original exchange a pigment, and so on, and then left to the final end of a switching element, this time well sort.
Time and space complexity
Time complexity is: O (N * logN)
space complexity is: O (1)
stability
Unstable
Code
#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;
}