JAVA
import java.util.Arrays;
public class Selection_Sort_Using_Template {
/**
* 算法描述:对于给定的一组记录,经过第一轮比较后得到最小的记录,然后将该记录与第一个记录的位置进行交换;
* 接着对不包括第一个记录以外的其他记录进行第二轮比较,得到最小的记录并与第二个记录进行位置交换; 重复该过程,直到进行比较的记录只有一个时为止。
*
* @param args
*/
public static void main(String[] args) {
Person_ p1 = new Person_(12);
Person_ p2 = new Person_(1);
Person_ p3 = new Person_(112);
Person_ p4 = new Person_(42);
Person_ p5 = new Person_(15);
Person_ p[] = { p1, p2, p3, p4, p5 };
System.out.println("排序之前");
System.out.println(Arrays.toString(p));
System.out.println("排序之后");
selectionSort(p);
System.out.println(Arrays.toString(p));
}
/*
* extends 在这里不表示继承的关系,而是类型的限定
*/
public static <T extends Comparable<T>> void selectionSort(T[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
// 寻找[i, n)区间里的最小值
int minIndex = i;// 用来记录最小值的索引位置,默认值为i
for (int j = i + 1; j < n; j++)
if (arr[minIndex].compareTo(arr[j]) > 0)
minIndex = j; // 遍历 i+1~length 的值,找到其中最小值的位置
// 交换当前索引 i 和最小值索引 minIndex 两处的值
if (minIndex != i) {
T tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
}
}
/**
* 用冒泡排序对任何对象排序 Comparable类 用于比较两个对象的大小
*
* @param x
* 对象
*/
class Person_ implements Comparable<Person_> {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person_(int age) {
super();
this.age = age;
}
@Override
public String toString() {
return " [age=" + age + "]";
}
@Override
public int compareTo(Person_ o) {
if (this.age == o.age)
return 0;
else if (this.age > o.age)
return 1;
else
return -1;
}
}
C++
#include <iostream>
#include "Student.h"
using namespace std;
template<typename T>
void selectionSort(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] = {10,9,8,7,6,5,4,3,2,1};
selectionSort( a , 10 );
for( int i = 0 ; i < 10 ; i ++ )
cout<<a[i]<<" ";
cout<<endl;
// 测试模板函数,传入浮点数数组
float b[4] = {4.4,3.3,2.2,1.1};
selectionSort(b,4);
for( int i = 0 ; i < 4 ; i ++ )
cout<<b[i]<<" ";
cout<<endl;
// 测试模板函数,传入字符串数组
string c[4] = {"D","C","B","A"};
selectionSort(c,4);
for( int i = 0 ; i < 4 ; i ++ )
cout<<c[i]<<" ";
cout<<endl;
// 测试模板函数,传入自定义结构体Student数组
Student d[4] = { {"D",90} , {"C",100} , {"B",95} , {"A",95} };
selectionSort(d,4);
for( int i = 0 ; i < 4 ; i ++ )
cout<<d[i];
cout<<endl;
return 0;
}
Student.h
#ifndef INC_02_SELECTION_SORT_USING_TEMPLATE_STUDENT_H
#define INC_02_SELECTION_SORT_USING_TEMPLATE_STUDENT_H
#include <iostream>
#include <string>
using namespace std;
struct Student{
string name;
int score;
bool operator<(const Student& otherStudent){
return score != otherStudent.score ?
score > otherStudent.score : name < otherStudent.name;
}
friend ostream& operator<<(ostream &os, const Student &student){
os<<"Student: "<<student.name<<" "<<student.score<<endl;
return os;
}
};
#endif