Table of contents
1.2 Direct Selection Sort Implementation Process
1.4 Directly select and sort the source code
2.1 The concept of heap sorting
foreword
Selection sort has two common [direct selection sort], [heap sort]
1. Direct selection sort
1.1 Basic idea
Advanced thinking: After traversing once, we can not only select the smallest number, but also the largest number
1.2 Direct Selection Sort Implementation Process
①: Select the data element with the largest ( smallest ) key code in the element set array[i]--array[n-1]②: If it is not the last ( first ) element in this group of elements, exchange it with the last (first) element in this group of elements③: In the remaining array[i]--array[n-2] ( array[i+1]--array[n-1] ) collection, repeat the above steps until there is 1 element left in the collection
1.3 Animation aids
selection sort
1.4 Directly select and sort the source code
void SelectSort(int* a, int n)
{
assert(a);
int begin = 0, end = n - 1;
while (begin < end)
{
int mini = begin, maxi = begin;
for (int i = begin + 1; i <= end; ++i)
{
if (a[i] < a[mini])
mini = i;
if (a[i] > a[maxi])
maxi = i;
}
Swap(&a[begin], &a[mini]);
// 如果begin和maxi重叠,那么要修正一下maxi的位置
if (begin == maxi)//如果走了这一步代表第一个数就是最大的
{
maxi = mini;
}
Swap(&a[end], &a[maxi]);
++begin;
--end;
}
}
1.5 Summary of features of direct selection sort
1. The direct selection and sorting thinking is very easy to understand, but the efficiency is not very good. rarely used in practice2. Time complexity: O(N^2) [The best and worst time complexities are both O(N^2)]3. Space complexity: O(1)4. Stability: Unstable
2. Heap sort
2.1 The concept of heap sorting
Why build a large pile?
Build a large heap, the top element of the heap is the largest number, let the top element of the heap exchange with the last element, and then adjust downwards, note: when adjusting downwards here, the adjusted array size is -1, that is, the adjustment just before the exchange The data
2.2 Heap sort source code
void HeapSort(int* a, int n)
{
// 建堆方式2:O(N)
for (int i = (n-1-1)/2; i >= 0; --i)
{
AdjustDwon(a, n, i);
}
// O(N*logN)
int end = n - 1;
while (end > 0)
{
Swap(&a[0], &a[end]);//这里的end是9,传过去向下调整的元素个数也是9,
//就不会调整刚刚从堆顶传下来的数据
AdjustDwon(a, end, 0);
--end;
}
The next article is exchange sort [bubble sort], [quick sort]
If you think the article is good, I look forward to your one-click triple link. Your encouragement is the source of motivation for my creation. Let us work together and see you at the top! ! !