時間複雜度爲 n*n,是一個穩定的排序算法,C++實現代碼如下(是經過優化的,不用每一趟中每次比較都交換一下數組):
#include <iostream> using namespace std; int BubbleSort(int *arr,int size); int main() { int arr[] = {4,3,2,1}; BubbleSort(arr,4); for(int a=0 ; a<4 ; a++) //遍歷輸出排序好的數組 { cout<<arr[a]; } return 0; } //當傳入的實參是地址類型時(如對象,數組等,結構體等,基本數據類型不算,用指針,其他用引用,這樣傳遞的參數纔是他自己,而不是拷貝) int swap(int &a,int &b) { int temp=a; a=b; b=temp; return 0; } int BubbleSort(int *arr,int size) { for(int i=0;i<size;i++) { int maxindex=0; //每次比較,保存較大那個值的索引 for(int j=0;j<size-i-1;j++) { if(arr[j]>arr[maxindex+1]) //關鍵!!!每次和最大的那個下標的值比,大的話,就記錄下J { maxindex=j; } } if(maxindex==0) //如果有一趟沒有交換(即最大的那個位置一直再第一個沒變),意味着已經有序了,無須再排 break; else { swap(arr[maxindex],arr[size-1-i]); } } return 0; }
輸出結果:4321Press any key to continue
直播概要: 隨着計算機的蓬勃發展,互聯網進入大數據和人工智能時代,爲了解決信息過載和長尾商品,推薦系統成爲唯一選擇,而面對不同的業務場景,爲了解決業務痛點,會根據不同的場景特點尋找不同的方法和手段來解決推薦中實際遇到的問題。在智慧家庭領域,
{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"typ
{"type":"doc","content":[{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null
{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockq