您的位置:首页 > 理论基础 > 数据结构算法

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

2017-10-14 20:14 363 查看
算法思想:

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

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

//选择排序
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_H

class 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: