Simple explanation of selection sort (1)

The core of direct selection sorting is to find the maximum value (or minimum value) in each traversal process. The outer traversal is to find the starting position of each traversal, and at the end of each traversal, it is used to store the extreme value found each time , but only record its subscript during the inner traversal process, and then use the exchange to place the most value at the head or tail of the array.

Selection sort is an         unstable sort

time complexity

The best time complexity of selection sort is O(n^2)

The worst time complexity of selection sort is O(n^2)

So the total average time complexity of selection sort is O(n^2)

#include<iostream>
#include<string>
using namespace std;
int main(){
	int n,a,temp,e,b[50];
	cin>>n;
	for(int k=0;k<n;k++){
		cin>>b[k];
	}
        for(int i=0;i<n-1;i++){
		a=i; //Get the initial subscript of the element to be compared each time
		for(int j=i+1;j<n;j++){
			if(b[a]<b[j])
				a=j; //If a larger (smaller) element is encountered in the comparison, the subscript is recorded
		} //After the traversal is completed, a stores the extreme value subscript of each traversal
		if(a!=i){ //Only every time the element at the starting position i is not the element at the extreme value a that is to be found, the exchange is performed (if the starting position is the extreme value, there is no need to exchange)
			temp=b[i];
			b[i]=b[a];
			b[a]=temp;
		}
	}
	for(int r=0;r<n;r++){
		cout<<b[r];
	}
	return 0;
}

Guess you like

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