选择排序(selectionSort)

#include<iostream>
#include<algorithm>
using namespace std;

//泛型模板函数
template<typename T> 
//排序输入参数:一个数组无论类型,一个数组容量大小。排序时使用下标的方式
void selectSort(T arr[], int n) {
	for (int i = 0; i < n; i++) {
		int minIndex = i;
		for (int j = i + 1; j < n; j++) {
			if (arr[j] < arr[minIndex])
				minIndex = j;	
		}
		swap(arr[i],arr[minIndex]);
	}
}

int main() {
	int a[10] = { 5,1,2,6,3,4,7,9,8,0 };
	selectSort(a,10);
	for (int i = 0; i < 10; i++) {
		cout << a[i] << endl;
	}
	//对浮点类型数组进行排序
	float b[4] = {1.1,6.1,2.3,3.1};
	selectSort(b, 4);
	for (int i = 0; i < 4; i++)
		cout << b[i] << endl;
	//对字符进行排序
	string k[3] = {"abc","aac","d"};
	selectSort(k,3);
	for (int i = 0; i < 3; i++)
		cout << k[i] << endl;
	return 0;
}

运算符重载方式
新建Student.h

#ifndef SELSETIONSORT_STUDENT_H
#define SELSETIONSORT_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 

.c代码:

#include<iostream>
#include<algorithm>
#include"Student.h"
using namespace std;

//泛型模板函数
template<typename T> 
//排序输入参数:一个数组无论类型,一个数组容量大小。排序时使用下标的方式
void selectSort(T arr[], int n) {
	for (int i = 0; i < n; i++) {
		int minIndex = i;
		for (int j = i + 1; j < n; j++) {
			if (arr[j] < arr[minIndex])
				minIndex = j;	
		}
		swap(arr[i],arr[minIndex]);
	}
}

int main() {
	int a[10] = { 5,1,2,6,3,4,7,9,8,0 };
	selectSort(a,10);
	for (int i = 0; i < 10; i++) {
		cout << a[i] << endl;
	}
	//对浮点类型数组进行排序
	float b[4] = {1.1,6.1,2.3,3.1};
	selectSort(b, 4);
	for (int i = 0; i < 4; i++)
		cout << b[i] << endl;
	//对字符进行排序
	string k[3] = {"abc","aac","d"};
	selectSort(k,3);
	for (int i = 0; i < 3; i++)
		cout << k[i] << endl;
	//结构体
	Student d[3] = { {"A",90},{"b",10},{"c",30}, };
	selectSort(d, 3);
	for (int i = 0; i < 3; i++)
		cout << d[i] << endl;
	return 0;
}

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值