C35-10.12复习回顾
原题链接:38471.note12025-10-12 17:59:13
发布于:江苏
一、上节课作业回顾
选择排序
#include <bits/stdc++.h>
using namespace std;
int main(){
int n,a[1005] = {};
cin>>n;
for(int i=1;i<=n;i++)cin>>a[i];
for(int i=1;i<=n;i++){
int k=i;
for(int j=i+1;j<=n;j++){
if(a[j]<a[k]){
k=j;
}
}
swap(a[i],a[k]);
}
for(int i=n;i>=1;i--)cout<<a[i]<<" ";
return 0;
}
排队照相
#include <iostream>
using namespace std;
int n, a[10005];
int main() {
cin >> n;
for (int i=1; i<=n; i++) cin >> a[i];
sort(a+1, a+n+1);
//输出男生
for (int i=1; i<=n; i++){
if (a[i]>0) cout<<a[i]<<' ';
}
//输出女生
for (int i=1; i<=n; i++){
if (a[i]<0) cout<<a[i]<<' ';
}
return 0;
}
/*
[【基础排序(二)】排队照相]
题目描述
小明的班级中有 n 个同学,
现在要进行集体合影,合影时,老师站在中间,
男同学均站在老师左侧从左至右按身高升序排列,
女同学均站在老师右侧,按身高降序排列。现在请你帮老师排好队伍。
样例说明:
男同学为145 140 180 ,
给男同学从小到大排序放在老师左边,
女同学为-155 和-150,从小到大放在老师右边。
输入格式
一行 n 个整数 h,表示每个同学的身高,
如果是正数,表示男同学,如果是负数,表示女同学
输出格式
n 个整数,表示排好序的队伍
样例组
输入#1
5
145 -155 140 180 -150
输出#1
140 145 180 -155 -150
提示
数据范围:
1≤n≤100,?200<h<200,h!=0
提示
数据范围:
1≤n≤100,?200<h<200,h!=0
*/
二、回顾
函数参数
#include<iostream>
using namespace std;
void f(int x, char ch){ //形参
cout << x << endl;
cout << ch << endl;
}
int main() {
f(23, 'k'); //参数 实际参数 实参
return 0;
}
函数的传参
#include<iostream>
using namespace std;
void f(int &x){
x = 10;
}
int main() {
int x = 100;
cout << x << endl;
// f(x); //1.值传递, 不改变原来的值
//2.引用传递, 能改变原来值
f(x);
cout << x << endl;
return 0;
}
位运算符
位运算符:
按位与: &
按位或: |
按位异或: ^
按位取反: ~
按位左移: <<
按位右移: >>
二进制按每一位进行计算
实例1: 排序
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e6+5;
int a[N], n, op;
int main() {
cin >> n;
for (int i=1; i<=n; i++) cin>>a[i];
cin >> op;
sort (a+1, a+1+n);
if (op == 1){ //降序输出
for (int i=n; i>=1; i--) cout<<a[i]<<' ';
}
else{ //升序输出
for (int i=1; i<=n; i++) cout<<a[i]<<' ';
}
return 0;
}
/*
[排序]
题目描述
给你 n 个 1~10^9的整数,
最后再用 0 来表示进行升序排序,
1 来表示降序排序,请输出最终的结果。
输入格式
第一行一个整数 n,n 最大不超过 10^6。
第二行共 n 个整数。
第三行要么是 0 要么是 1。
输出格式
请输出最终的排序结果
样例组
输入#1
6
1 2 3 4 5 6
1
输出#1
6 5 4 3 2 1
输入#2
输出#2
6
4 3 1 5 6 2
0
1 2 3 4 5 6
*/
实例2:二进制中1的距离
#include <iostream>
using namespace std;
int n, a[100005], idx=1;
int main() {
cin >> n;
while (n){
a[idx++] = n%2;
n /= 2;
}
int l, r;
for (int i=1; i<idx; i++){
if (a[i] == 1){
l = i; //左边的1
break;
}
}
for (int i=idx-1; i>=1; i--){
if (a[i] == 1){
r = i; //右边的1
break;
}
}
cout << r - l;
return 0;
}
这里空空如也
有帮助,赞一个