Introduction
English name: Select Sort
is the simplest algorithm in selection sort
step
The following uses the array 2,5,8,3,6,9,1,4,7 as an example
to sort from small to large
1. Find the smallest number in the unsorted part
- At the beginning, it is regarded as all out of order, starting from the first one out of order
- find the smallest number 1
2. Look at the position of the smallest number found, if it is not the first one in the unsorted part, exchange it with the first one
- Now 1 is not the first, so we swap it with 2
3. Repeat the first two steps until all numbers are sorted
-
1 has been arranged, so the next step is the random part from the second number, repeat the first two steps from the second number
-
find the smallest number 2
- swap with the previous number
- continue
The following steps are also very simple, no longer given
the code
- First of all, we need to perform n-1 traversals to arrange each number (only the last number is left without ordering)
- Use a k to record the subscript of the minimum number of the current disordered part
- Start traversing from the second number to find the smallest number, and compare it with the number marked by k
- If the minimum subscript is not the first in random order, exchange the two numbers
#include<bits/stdc++.h>
using namespace std;
void SelectSort(int a[],int len)
{
int k;
for(int i=0;i<len-1;i++)//未排序第一个数
{
k=i;//取第一个数
for(int j=i+1;j<len;j++)//遍历未排序部分
if(a[j]<a[k])
k=j;//取更小
if(i!=k)//不在未排序第一的位置
swap(a[k],a[i]);
for(int t=0;t<len;t++)
cout<<a[t]<<" ";
cout<<endl;
}
}
int main()
{
int a[9]={
2,5,8,3,6,9,1,4,7};
int len=9;
SelectSort(a,len);
return 0;
}
characteristic
1. Time complexity
O ( n 2 ) O(n^2)O ( n2)
2. Space complexity
The average space complexity is: O ( 1 ) O(1)O(1)
3. Algorithm stability
Does the order of the same elements change?
Give a very simple example
In the picture above, blue 1 will be exchanged with blue 2, directly changing the front and rear positions of the two 2s
So simple selection sort sorting is unstable
Quiz
long time no see quiz
The old rule, now is to exchange the minimum number to the front, and change the maximum number to the back
Chong Chong Chong ψ(`∇´)ψ