算法理解:给你长度为n的一个数组a【】,输出n个值,分别为a[0]-a[i](0<=i<n)的最大值
如:
| 2 | 1 | 3 | 5 | 4 |
2 最大值为2
2 1 最大值为2
2 1 3 最大值为3
2 1 3 5 最大值为5
2 1 3 5 4 最大值为5
所以输出应该使2 2 3 5 5
这时候就要用到冒泡排序(不难看出选择排序也可以实现这个功能),冒泡排序的过程如下
| 2 | 1 | 3 | 5 | 4 |
| 1 | 2 | 3 | 5 | 4 |
| 1 | 2 | 3 | 5 | 4 |
| 1 | 2 | 3 | 5 | 4 |
| 1 | 2 | 3 | 4 | 5 |
从第一个数字开始,像一个泡泡一样遇到比自己小的数字就交换位置,可以发现,1.进行到第i位时,数组的第i位就是前i项的最大值,2.进行一次遍历后数组的最大值在数组的末尾。
数组的最大值在数组的末尾是十分友好的,意味着如果进行n次此过程,数组就可以变成有序数组
冒泡排序代码:
#include <algorithm>
#include <iostream>
#include <cstring>
#include <vector>
#include <cstdio>
#include <cmath>
using namespace std;
const int maxn=1e4+10;
int a[maxn];
int main(){
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
for(int i=0;i<n-1;i++){
for(int j=0;j<n-1;j++){
if(a[j]>a[j+1]){
swap(a[j],a[j+1]);
}
}
}
for(int i=0;i<n;i++){
printf("%d ",a[i]);
}printf("\n");
return 0;
}
例一:求逆序对对数
#include <algorithm>
#include <iostream>
#include <cstring>
#include <vector>
#include <cstdio>
#include <cmath>
using namespace std;
const int maxn=1e4+10;
int a[maxn];
//有意思的是冒泡排序的交换次数就是逆序对对数
int main(){
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
int num=0;
for(int i=0;i<n-1;i++){
for(int j=0;j<n-1;j++){
if(a[j]>a[j+1]){
swap(a[j],a[j+1]);
num++;
}
}
}
printf("%d\n",num);
/*
for(int i=0;i<n;i++){
printf("%d ",a[i]);
}printf("\n");
*/
return 0;
}