A brief explanation of bubble sort (2)

The name of this algorithm comes from the fact that larger elements will slowly "float" to the top of the sequence by swapping, hence the name "bubble sort".

time complexity

The best time complexity of bubble sort is O(n)

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

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

c++ implementation is as follows

#include<iostream>
#include<string>
using namespace std;
int main(){
	int a[10];
	int n,temp;
	cin>>n;//sort n numbers
	for(int k=0;k<n;k++){
		cin>>a[k];
	}
	
//core code
	for(int i=0;i<n-1;i++){
            //Because the outer traversal compares the value with the last element taken out in the inner layer, the value is one less than the number of elements
		for(int j=i+1;j<n;j++){
			if(a[j]>a[i]){ //Swap if the conditions are met, use >< depending on how you want to arrange
				temp=a[j];
				a[j]=a[i];
				a[i]=temp;
			}
		}
	}

	for(int m=0;m<n;m++){
		cout<<a[m];//Print
	}
	cout<<endl;
	return 0;
}

Guess you like

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