选择排序主要有: (1)直接选择排序 (2)堆排序 直接选择排序: #include<iostream> #include<vector> using namespace std; class SelectSort { private: int len; vector<int> list; public: SelectSort(vector<int> m_list,int m_len); void selct_sort(); void swap(int,int); void out(); }; SelectSort::SelectSort(vector<int> m_list, int m_len) { len=m_len; for(int i=0;i<len;i++) { list.push_back(m_list[i]); } } void SelectSort::selct_sort() { int k; for(int i=0;i<len;i++) { k=i; for(int j=i+1;j<len;j++)//找最小的元素 if(list[j]<list[k]) k=j; swap(i,k); } } void SelectSort::swap(int i, int j) { int temp=list[i]; list[i]=list[j]; list[j]=temp; } void SelectSort::out() { vector<int>::iterator it; for(it=list.begin();it!=list.end();it++) { cout<<*it<<endl; } } int main() { vector<int> list; list.push_back(20); list.push_back(37); list.push_back(50); list.push_back(35); list.push_back(10); list.push_back(1); SelectSort ss(list,list.size()); ss.selct_sort(); ss.out(); } 堆排序: #include<iostream> #include<vector> using namespace std; class HeapSort { private: int len; vector<int> list; public: HeapSort(vector<int>m_list,int m_len); void heap_sort(); void filterDown(int current,int last); void swap(int,int); void out(); }; HeapSort::HeapSort(vector<int> m_list, int m_len) { len=m_len; for(int i=0;i<len;i++) { list.push_back(m_list[i]); } } void HeapSort::heap_sort() { for(int i=(len-2)/2;i>=0;i--) filterDown(i,len-1); for(int i=len-1;i>0;i--) { swap(0,i); filterDown(0,i-1); } } void HeapSort::filterDown(int current, int last) { int child=2*current+1; int temp=list[current]; while(child<=last) { if(child<last&&list[child]<list[child+1]) child++; if(temp>=list[child]) break; else { list[current]=list[child]; current=child; child=2*child+1; } list[current]=temp; } } void HeapSort::swap(int i, int j) { int temp=list[i]; list[i]=list[j]; list[j]=temp; } void HeapSort::out() { vector<int>::iterator it; for(it=list.begin();it!=list.end();it++) { cout<<*it<<endl; } } int main() { vector<int> list; list.push_back(20); list.push_back(37); list.push_back(50); list.push_back(35); list.push_back(10); list.push_back(1); HeapSort hs(list,list.size()); hs.heap_sort(); hs.out(); }