c++数组排序_算法综合1排序基础

1. 选择排序

选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理是:第一次从待排序的数据元素中选出最小(最大)的一个元素,存放在序列的起始位置,然后再从剩余的未排序元素中寻找到最小(大)元素,然后放到已排序的序列的末尾。以此类推,直到全部待排序的数据元素的个数为零。

1)初始无序数据:5af22ff6f2863b331ee008bce7cd9f26.png2)第一次排序:c5ba0d0a35b1292140ef107a027d24b5.png3)第二次排序:71713f23a6f0f2bf57a7da1556798496.png4)以此类推:ef26dfc962ad79ff895615ca3730e941.png

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      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值