【基礎排序】選擇排序
阿新 • • 發佈:2019-01-05
#include <iostream> using namespace std; void SelectionSort(int a[],int n) { for(int i=0; i<n-1; ++i) { int k=i; for(int j=i+1; j<n; j++) { if(a[k]>a[j]) { k=j; } } if(k!=i) { swap(a[k],a[i]); } } } void print(int a[],int n) { for(int i=0; i<n; i++) { cout<<a[i]<<" "; } cout << endl; } void main() { int a[] = {1,3,6,8,0,5,7}; cout << "排序前:"; print(a,sizeof(a)/sizeof(a[0])); SelectionSort(a,sizeof(a)/sizeof(a[0])); cout << "排序後:"; print(a,sizeof(a)/sizeof(a[0])); }