這題雖然有更好的算法(merge sort+反序數對),但用氣泡就可以了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| void countSwaps(vector<int> a) { int ct=0; for(int i=0;i<a.size();i++){ for (int j=0;j<a.size()-1;j++){ if (a[j]>a[j+1]){ ct++; swap(a[j],a[j+1]); } } } cout<<"Array is sorted in "<<ct<<" swaps."<<"\n"; cout<<"First Element: "<<a[0]<<"\n"; cout<<"Last Element: "<<a[a.size()-1]; return; }
|