算法基础知识——排序与查找
目录:
- 基础知识
- 排序(基本类型、结构体或类)
- 查找(线性查找、二分查找)
- 应用实例
- 排序【华中科技大学】
- 成绩排序【清华大学】
- 成绩排序2【清华大学】
- 特殊排序【华中科技大学】
- 整数奇偶排序【北京大学】
- 小白鼠排队【北京大学】
- 奥运拍讯问题【浙江大学】
- 找x【浙江大学】
- 查找【北京邮电大学】
- 找最小数【北京邮电大学】
- 打印极值点下标【北京大学】
- 找位置【华中科技大学】
一、基础知识
1、排序
- 基本类型的排序:对整型、浮点型等计算机编程语言内置的基本类型进行排序
- 结构体或类的自定义排序:
- 方法一:设计比较函数
- 方法二:在结构体或类的内部重载小于号
2、查找
- 先通过排序,方便查找。
- 查找的基本要素:
- 查找空间(解空间):在查找空间中找寻复合要求的解。
- 查找目标:需要一个目标来判断查找空间中的各个元素是否符合要求,以便判断查找活动是否成功。
- 查找方法:利用某种特定的策略在查找空间中查找各个元素。
- 常用查找方法:
- 线性查找:多次(m次)查找时间复杂度:O(mn)
- 二分查找:多次(m次)查找时间复杂福:O(nlogn + mlogn)
- 当m达到一定程度时,二分查找的性能远优于线性查找。
二、应用实例
1、题目描述:对输入的n个数进行排序并输出。【华中科技大学】
- 输入格式:输入的第一行包括一个整数n(1<=n<=100)。接下来的一行包括n个整数。
- 输出格式:可能有多组测试数据,对于每组数据,将排序后的n个整数输出,每个数后面都有一个空格。每组测试数据的结果占一行。
- 样例输入:
- 4
- 1 4 3 2
- 样例输出:
- 1 2 3 4
示例代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> myVector;
int main(){
int n, input;
while(cin >> n){
for(int i = 0; i < n; i++){
cin >> input;
myVector.push_back(input);
}
sort(myVector.begin(), myVector.end());
for(vector<int>::iterator iter = myVector.begin(); iter != myVector.end(); iter++){
cout << *iter << " ";
}
cout << endl;
myVector.clear();
}
return 0;
}
2、题目描述:用一维数组存储学号和成绩,然后,按成绩排序输出。【清华大学】
- 输入格式:输入第一行包括一个整数N(1<=N<=100),代表学生的个数。接下来的N行每行包括两个整数p和q,分别代表每个学生的学号和成绩。
- 输出格式:按照学生的成绩从小到大进行排序,并将排序后的学生信息打印出来。如果学生的成绩相同,则按照学号的大小进行从小到大排序。
- 样例输入:
- 3
- 1 90
- 2 87
- 3 92
- 样例输出:
- 2 87
- 1 90
- 3 92
示例代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Student{
int number;
int score;
Student(int n, int s):number(n), score(s){};
bool operator<(const Student &stu);
};
vector<Student> stuVector;
bool Student::operator<(const Student &stu){
if(score < stu.score){
return true;
}else if(score == stu.score){
return number < stu.number;
}else{
return false;
}
}
int main(){
int n, number, score;
while(cin >> n){
for(int i = 0; i < n; i++){
cin >> number >> score;
Student stu(number, score);
stuVector.push_back(stu);
}
sort(stuVector.begin(), stuVector.end());
for(vector<Student>::iterator iter = stuVector.begin(); iter != stuVector.end(); iter++){
cout << (*iter).number << " " << iter->score << endl;
}
stuVector.clear();
}
return 0;
}
3、题目描述:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩都按先录入排列在前的规则处理。【清华大学】
- 输入格式:输入多行,先输入要排序的人的个数,然后输入排序方法0(降序)或者1(升序)再分别输入他们的名字和成绩,以一个空格隔开
- 输出格式:按照指定方式输出名字和成绩,名字和成绩之间以一个空格隔开
- 样例输入:
- 3
- 0
- fang 90
- yang 50
- ning 70
- 样例输出:
- fang 90
- ning 70
- yang 50
示例代码:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
struct Student{
string name;
int score;
int order;
Student(string n, int s, int o):name(n), score(s), order(o){};
};
vector<Student> stuVector;
bool CompareAsc(const Student &stuA, const Student &stuB){
if(stuA.score != stuB.score){
retu