数据结构与算法-排序:选择排序

来源:互联网 发布:tensorflow最新版本 编辑:程序博客网 时间:2024/05/19 05:33

算法思想:
我就从所有序列中先找到最小的,然后放到第一个位置,之后再看剩余元素中最小的,放到第二个位置……以此类推

查找最小元素的索引,跟第一个位置的元素替换,每次往后找最小的元素的索引

//选择排序     template<typename T>    void selectionSort(T arr[],int n){        //优化代码         for(int j=0;j<n;j++){            //T min=arr[j];            //int k=j;            int minIdx=j;            for(int i=j+1;i<n;i++){                if(arr[i]<arr[minIdx]){                    //min=arr[i];                    //k=i;                    minIdx=i;                }            }            //arr[k]=arr[j];            //arr[j]=min;            swap(arr[j],arr[minIdx]);        }

对象排序
创建一个学生对象,重写小于运算符

#ifndef SOMETHING_H#define SOMETHING_Hclass Student {    // Private section    public:        string name;        int score;    friend ostream& operator<<(ostream &os,const Student stu){        os<<"Student :"<<stu.name<<","<<stu.score<<endl;        return os;    }    bool operator<(const Student &otherStu){        return score!=otherStu.score?score>otherStu.score:name<otherStu.name;    }};#endif
#include <iostream>#include "Student.h"/* run this program using the console pauser or add your own getch, system("pause") or input loop */using namespace std;int main(int argc, char** argv) {       Student stuArr[]={{"D",80},{"F",70},{"A",90},{"B",80}};    SortTestHelper::printArray(stuArr,4);    SortTestHelper::selectionSort(stuArr,4);    SortTestHelper::printArray(stuArr,4);    return 0;}template<typename T>    void printArray(T arr[],int n){        for(int i=0;i<n;i++){            cout<<arr[i]<<" ";        }        cout<<endl;        return;    }