1. 選擇排序html
選擇排序(Select sort)是一種簡單直觀的排序算法。工做原理以下。首先在未排序序列中找到最小元素,存放到排序序列的起始位置,而後,再從剩餘未排序元素中繼續尋找最小元素,而後放到已排序序列的末尾。以此類推,直到全部元素均排序完畢。【詳情見維基百科】ios
選擇排序的特色:算法
選擇排序的示例動畫以下。紅色表示當前最小值,黃色表示已排序序列,藍色表示當前位置。測試
#include<iostream> #include<vector> using namespace std; void SelectSort(vector<int> &array){ for(int i = 0; i < array.size(); i++){ int idxOfMin = i; for(int j = i + 1; j < array.size(); j++){ if(array[j] < array[idxOfMin]) idxOfMin = j; } swap(array[i], array[idxOfMin]); } } int main(int argc, char const *argv[]) { vector<int> a1 = {5, 9, 0, 1, 3, 6, 4, 8, 2, 7}; SelectSort(a1); for(auto &it : a1) cout<<it<<' '; cout<<endl; return 0; }
3.採用大量隨機數據進行測試 動畫
#include<iostream> #include<vector> #include <stdlib.h> #include <time.h> using namespace std; void SelectSort(vector<int> &array){ for(int i = 0; i < array.size(); i++){ int idxOfMin = i; for(int j = i + 1; j < array.size(); j++){ if(array[j] < array[idxOfMin]) idxOfMin = j; } swap(array[i], array[idxOfMin]); } } // 判斷array是否有序 bool isOrder(vector<int> &array){ for(int i = 1; i < array.size(); i++){ if(array[i] < array[i-1]) return false; } return true; } // 生成n個介於min,max之間的整型數 vector<int> RAND(int max, int min, int n) { vector<int> res; srand(time(NULL)); // 註釋該行以後,每次生成的隨機數都同樣 for(int i = 0; i < n; ++i) { int u = (double)rand() / (RAND_MAX + 1) * (max - min) + min; res.push_back(u); } return res; } // 使用200000個介於1,10000之間的數據進行測試 int main(int argc, char const *argv[]) { vector<int> a = RAND(1, 10000, 200000); clock_t start = clock(); SelectSort(a); clock_t end = clock(); cout << "Time goes: " << (double)(end - start) / CLOCKS_PER_SEC << "sec" << endl; bool sorted = isOrder(a); cout<<sorted<<endl; return 0; }
測試結果以下:spa
Time goes: 184.319sec 1 [Finished in 185.6s]
可見,對200000(20萬)個數據排序耗時184.3sec 。這通常是由於選擇排序在最好和最壞狀況下的時間複雜度都是O(n2)所致。而使用堆排序對20000000(2千萬)個數據排序只用了25.2sec。【點擊此處查看堆排序】3d
【點擊此處查看經常使用排序算法】code