#include<bits/stdc++.h>usingnamespace std;intmain(){int n, a[25];cin >> n;for(int i =1; i <= n;++i)cin >> a[i];for(int i =1; i <= n-1;++i)for(int j =1; j <= n-i;++j){if(a[j]< a[j+1])swap(a[j], a[j+1]);}for(int i =1; i <= n;++i)cout << a[i]<< endl;return0;}
數(shù)組下標(biāo)0~n-1 i從0到n-1,j從0到n-i-1(這里的‘到’指小于)
#include<bits/stdc++.h>usingnamespace std;intmain(){int n, a[25];cin >> n;for(int i =0; i < n;++i)cin >> a[i];for(int i =0; i < n-1;++i)for(int j =0; j < n-i-1;++j){if(a[j]< a[j+1])swap(a[j], a[j+1]);}for(int i =0; i < n;++i)cout << a[i]<< endl;return0;}
解法2:
符合冒泡概念的版本
數(shù)組下標(biāo)1~n:
#include<bits/stdc++.h>usingnamespace std;intmain(){int n, a[25];cin >> n;for(int i =1; i <= n;++i)cin >> a[i];for(int i = n; i >=2;--i)//這次循環(huán)要確定的數(shù)的最終位置for(int j =1; j <= i -1;++j)//要交換的數(shù)對(duì)的第一個(gè)數(shù){if(a[j]< a[j+1])swap(a[j], a[j+1]);}for(int i =1; i <= n;++i)cout << a[i]<< endl;return0;}
數(shù)組下標(biāo)0~n-1
#include<bits/stdc++.h>usingnamespace std;intmain(){int n, a[25];cin >> n;for(int i =0; i < n;++i)cin >> a[i];for(int i = n-1; i >=1;--i)for(int j =0; j <= i-1;++j){if(a[j]< a[j+1])swap(a[j], a[j+1]);}for(int i =0; i < n;++i)cout << a[i]<< endl;return0;}新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎(jiǎng)!定制產(chǎn)品紅包拿不停!