1. 选择排序
选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理是:第一次从待排序的数据元素中选出最小(最大)的一个元素,存放在序列的起始位置,然后再从剩余的未排序元素中寻找到最小(大)元素,然后放到已排序的序列的末尾。以此类推,直到全部待排序的数据元素的个数为零。
1)初始无序数据:2)第一次排序:
3)第二次排序:
4)以此类推:
1.1 代码实现
#include #include // 旧标准, 包含swapusing namespace std; // C++ 11标准,内置swapvoid selectionSort(int arr[], int n){
for(int i = 0; i // 寻找[i,n)区间的最小值所在索引 int minIndex = i; for(int j = i+1; j if(arr[j] < arr[minIndex]) minIndex = j; } swap(arr[i],arr[minIndex]); // C++ 11标准库内置,交换两位置的元素 }}int main(int argc, const char * argv[]) {
int a[10] = {
4,7,10,3,2,1,6,8,5,9}; selectionSort(a, 10); for (int i=0; i<10; i++) {
cout<" "; } cout<<endl; cout << "Hello, World!\n"; return 0;}
1.2 模版(泛型)
上述实现只适用于整型数组,C++中可以使用模版编程扩大适用范围(等价于Java中泛型的概念),包括整型、浮点型、字符型、复合型等等。
自定义Student:
// 宏定义,解决有可能出现的头文件多重引用问题#ifndef Student_h#define Student_husing namespace std; // 有可能出现命名空间污染struct Student{
string name; int score; // 对小于运算符重载,使结构体可以进行比较(Java中的Compareto) bool operatorconst Student &otherStudent){
// return score < otherStudent.score; // 分数由低到高排列 // return score > otherStudent.score; // 分数由高到低排列 return score!= otherStudent.score ? score > otherStudent.score : name < otherStudent.name; // 三目运算符,分数相同时使用字符串的字典序 } // 打印输出结果,对输出运算符进行重载(Java中的toString) friend ostream& operator<const Student &student){
os<<"Student:"<" "< return os; } };#endif /* Student_h *c z
测试:
#include #include // 旧标准, 包含swap#include // 旧标准,包含string#include "Student.h" // 自己编写的h文件,使用双引号using namespace std; // C++ 11标准,内置swaptemplate<typename T> // 模版函数,泛型void selectionSort(T arr[], int n){
for(int i = 0; i // 寻找[i,n)区间的最小值所在索引 int minIndex = i; for(int j = i+1; j