Selection Sort

Its working principle is to select the smallest (or largest) element from the data elements of the unordered group each time, and store it in the starting position of the unordered group. The elements of the unordered group decrease, and the elements of the ordered group increase until all the The data elements to be sorted are exhausted.

write picture description here

#include<iostream>
#include<algorithm>
using namespace std;

void selectionSort(int arr[],int n){
    for(int i =0;i < n;i++){
        //寻找[i,n)区间里的最小值 
        int minIndex = i;
        for(int j = i+1;j<n;j++){
            if(arr[j] < arr[minIndex]){
                minIndex=j;
            }
            //1.如果是c++ 11这个标准 这个函数在using namespace std;命名空间中
            //2.如果是之前的在#include<algorithm>
            //3.也可以自己交换
            swap(arr[i],arr[minIndex]);
        }
    }
}
int main(){

    int a[10]={10,9,8,7,6,5,4,3,2,1};
    selectionSort(a,10);
    for(int i = 0;i <10;i++){
        cout << a[i] << " ";
    }
    cout << endl;
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324693758&siteId=291194637