Sorting Algorithm (Selective Sort Algorithm)


1. What is selection sort?

Selection sort (Selection> sort) is a simple and intuitive sorting algorithm. Working principle : The smallest (largest) element is selected from the data elements to be sorted for the first time , stored in the starting position of the sequence, and then the smallest (largest) element is found from the remaining unsorted elements , and then placed in The end of the sorted sequence. And so on, until the number of all data elements to be sorted is zero. Selection sort is an unstable sorting method.
( Baidu Encyclopedia )

Selection sort is a relatively simple and easy-to-understand sorting algorithm that does not require additional storage space.
Note: Due to its time complexity is too large, it is not recommended to use it for sorting .

1. The complexity of the algorithm is as follows:

  • Time complexity O(n^2)
  • Space complexity O(1)

2. Algorithm principle

1. Animation display:

insert image description here

2. Speaking human words:

This algorithm will perform N searches on the array to be sorted, and each time will find the smallest (largest) value in the array to be sorted and place it behind the previously sorted data.


Summary and real machine code (C version)

Code display:

#include <stdio.h>
 
int main()
{
    
    
    int arr[10] = {
    
     10,9,8,7,6,5,4,3,2,1 }; //待排序数组
    
    int tmp = 0; //用来存储找到的最小值的下标
    //选择排序
    for (int i = 0; i < 10; i++)
    {
    
    
        tmp = i;
        for (int j = i; j < 10; j++)    //寻找待排序数据中的最小(大)值
        {
    
    
            if (arr[j] < arr[tmp])
            {
    
    
                tmp = j;
            }
        }
        int p = arr[tmp];
        arr[tmp] = arr[i];
        arr[i] = p;
    }
    for (int i = 0; i < 10; i++)
    {
    
    
        printf("%d ", arr[i]);
    }
    return 0;
}

Running result display:
insert image description here

Guess you like

Origin blog.csdn.net/2302_76339343/article/details/130919106