選擇排序也是一種簡單排序。這種排序的演算法是:首先找出最大的元素,把它移動交換到a[n-1],然後在餘下的n-1個元素中選擇最大的元素並把它移動交換到a[n-2],如此迭代下去即可完成排序。代碼如下:
// BubbleSort.cpp : 定義控制台應用程式的進入點。//
// SelectionSort.cpp : 定義控制台應用程式的進入點。//#include "stdafx.h"#include <cmath>#include <iostream>using namespace std;#define MAXNUM 20template<typename T>void Swap(T& a, T& b){ int t = a; a = b; b = t;}template<typename T>int Max(T a[], int n){//尋找數組a[0:n-1]中最大元素的位置 int pos = 0; for(int i =1 ;i < n; i++) { if(a[pos] < a[i]) pos = i; } return pos;}template<typename T>void SelectSort(T a[],int n){//對數組a[0:n-1]中的n個元素進行選擇排序 for(int size = n;size > 1; size--) { int j = Max(a,size); Swap(a[j],a[size-1]); } }int _tmain(int argc, _TCHAR* argv[]){ int a[MAXNUM]; for(int i = 0 ;i< MAXNUM; i++) { a[i] = rand()%(MAXNUM*5); } for(int i =0; i< MAXNUM; i++) cout << a[i] << " "; cout << endl; SelectSort(a,MAXNUM); cout << "After BubbleSort: " << endl; for(int i =0; i< MAXNUM; i++) cout << a[i] << " "; cin.get(); return 0;}