簡單選擇排序采用最簡單的選擇方法,即在剩余序列中選出最小(或最大)的關鍵字,和剩余序列的第一個關鍵字交換位置,依次選擇下去,直至使整個序列有序。
算法中兩層循環的執行次數和初始序列沒有關系,第二層循環每一次都需要遍歷剩余帶排序序列,故時間復雜度為O(n2)
直接上代碼:
#include<iostream> #include<string> using namespace std; template <typename T> void selectionSort(T arr[],int n){ for(int i=0;i<n;i++){ //尋找[i,n)區間里的最小值 int minIndex=i; //為最小值的位置做個標記 for(int j=i+1;j<n;j++) if(arr[j]<arr[minIndex]) minIndex=j; swap(arr[i],arr[minIndex]); } } int main(){ int array[10]={10,9,8,7,6,5,4,3,2,1}; selectionSort(array,10); for(int i=0;i<10;i++) cout<<array[i]<<" "; cout<<endl; float a[3]={3.3f,2.2f,1.1f}; selectionSort(a,3); for(int j=0;j<3;j++) cout<<a[j]<<" "; cout<<endl; string b[4]={"D","C","B","A"}; selectionSort(b,4); for(int k=0;k<4;k++) cout<<b[k]<<" "; cout<<endl; return 0; }
對於簡單選擇排序,一趟排序后能確保一個關鍵字到達其最終位置。