选择排序思路在于选择
先认为第一个数是最大值
将当前最大值序号存在一个变量中
将剩下的数依次与最大值比较
比较到最后将最大值序号指向数与当前第一个数交换
#include <iostream> #include <sstream> using namespace std; template<typename T> void selection_sort (T * array, int len,bool ascending) { T tmp = 0; int pos = 0; if(ascending) { for(int i = 0; i < len-1; i ++) { pos = i; for(int j = i + 1; j < len; j++) { if(array[j]>array[pos]) pos = j; } if(pos!=i) { tmp = array[i]; array[i] = array[pos]; array[pos] = tmp; } } } else { for(int i = 0; i < len-1; i ++) { pos = i; for(int j = i + 1; j < len; j++) { if(array[j]<array[pos]) pos = j; } if(pos!=i) { tmp = array[i]; array[i] = array[pos]; array[pos] = tmp; } } } } int main(int arc,char** argv) { if(arc<2) { cerr<<"argument is not enough"<<endl; return 1; } string str = argv[1]; stringstream ss; ss <<str; int number; ss >> number; cout << "number:" << number <<endl; float * data = new float[number]; for(int i = 0; i<number;i++) cin>>data[i]; cout<<"data"<<endl; for(int i = 0; i<number;i++) cout<<data[i]<<endl; selection_sort<float>(data,number,true); cout<<"sorted data"<<endl; for(int i = 0; i<number;i++) cout<<data[i]<<endl; delete [] data; return 0; }