c语常用算法库(1)

时间:2023-12-15 16:45:50

1,冒泡排序

 #include <iostream>
using namespace std; int main(){
int n, a[]; // 一共n个数, n不超过1000. a用来保存这些数.
int i = , j = ; // 循环变量
cin >> n;
// 输入n个数
for (i = ; i < n; i++)
cin >> a[i];
// 冒泡,不断比较相邻的两个数,如果顺序错了,那么就交换
for (i = ; i < n - ; i++)
for (j = ; j < n - i; j++){
if (a[j - ] > a[j]){
int temp = a[j];
a[j] = a[j - ];
a[j - ] = temp;
}
}
// 依次输出
for (i = ; i < n; i++){
cout << a[i] << endl;
}
return ;
}

2, 倒序输出

 #include<iostream>
using namespace std; int main() {
int n;
cin >> n;
int i, x[];
for ( i = ; i < n; i++)
cin >> x[i];
while ( n-- > ){
cout << x[n] << " ";
}
return ;
}