推荐慕课网,刘宇波老师《算法与数据结构》
链接:http:
selectionSort 课堂笔记
#include <iostream>
using namespace std;
#include<stdio.h>
#include"Student.h"
template<
typename T>
void SelectionSort(T arr[],
int n){
for(
int i=
0;i<n;i++)
{
int index = i;
for(
int j = i+
1;j<n;j++)
{
if(arr[j] < arr[index])
index = j;
}
if(index != i)
swap(arr[i],arr[index]);
}
}
int main()
{
int arr[] = {
10,
9,
8,
7,
6,
5,
4,
3,
2,
1};
int n =
sizeof(arr)/
sizeof(arr[
0]);
SelectionSort(arr,n);
for(
int i=
0;i<n;i++)
printf(
"%d ",arr[i]);
printf(
"\n");
double arr2[] = {
10.1,
9.5,
3.3};
int n2 =
sizeof(arr2)/
sizeof(arr2[
0]);
SelectionSort(arr2,n2);
for(
int i=
0;i<n2;i++)
printf(
"%.2f ",arr2[i]);
printf(
"\n");
string c[] = {
"D",
"A",
"C",
"B"};
int n3 =
sizeof(c)/
sizeof(c[
0]);
SelectionSort(c,n3);
for(
int i=
0;i<n3;i++)
cout<<c[i]<<
" ";
printf(
"\n");
Student st[
3] = {{
"B",
80},{
"C",
95},{
"A",
90}};
SelectionSort(st,
3);
for(
int i=
0;i<
3;i++)
cout<<st[i];
cout<<endl;
return 0;
}
#ifndef SELECTIONSORT_STUDENT_H
#define SELECTIONSORY_STUDENT_H
#include<iostream>
#include<string>
using namespace std;
struct Student{
string name;
int score;
bool operator<(
const Student &otherStudent){
return score<otherStudent.score;
}
friend ostream&
operator<<(ostream &os,
const Student &student){
os<<
"Student: "<<student.name<<
" "<<student.score<<endl;
return os;
}
};
#endif