1. 程式人生 > 其它 >57.C++直接選擇排序

57.C++直接選擇排序

技術標籤:C++c++

#pragma once
#ifndef _9_12_H
#define _9_12_H

//輔助函式交換x,y的值
template<class T>
void mySwap(T &x, T &y) {
	T temp = x;
	x = y;
	y = temp;
}
//直接選擇排序
template<class T>
void selectionSort(T a[], int n) {
	for (int i = 0; i < n; i++) {
		int leastIndex = i;
		//在元素a[i+1]到a[n-1]找出最小值
		for (int j = i + 1; j < n; j++) {
			if (a[j] < a[leastIndex]) {
				leastIndex = j;
			}
			mySwap(a[i], a[leastIndex]);
		}
	}
}






#endif // !_9_12_H