Algorithmic Implementation series(2)——Implementation of Selection_sort

来源:互联网 发布:linux scp传文件夹 编辑:程序博客网 时间:2024/06/06 03:28

Compiler: gcc 4.7.3

C++11

  1 #include <iostream>
  2 
  3 using namespace std;
  4 
  5 template <typename T>
  6 void show(T &t) {
  7     for(auto i : t) {
  8         cout << i << endl;
  9     }
 10 }
 11 
 12 
 13 void SELECTION_SORT(int ia[], const size_t size) {
 14     //If ia is empty or only contain one element, 
 15     //just return.                                                                            
 16     if(size == 0 || size == 1) {
 17         return;
 18     }
 19 
 20     for(size_t i = 0; i != size - 1; ++i) {
 21         int key = ia[i];
 22         size_t j = i;
 23         size_t k = j;//Storing the position of the min-value.
 24         while(j != size - 1) {
 25             //Record the value and position of the smallest 
 26             //element in current loop.
 27             if(key > ia[j + 1]) {
 28                 key = ia[j + 1];
 29                 k = j + 1;
 30             }
 31             ++j;
 32         }
 33         //Exchanging the values of the ith element 
 34         //and the kth element of array ia.
 35         key = ia[i];
 36         ia[i] = ia[k];
 37         ia[k] = key;
 38 
 39     }
 40 }
 41 
 42 
 43 
 44 int main() {
 45     int ia[6] = {4, 5, 2, 1, 6, 3};
 46     show(ia);
 47     cout << "====================" << endl;
 48 
 49     SELECTION_SORT(ia, sizeof(ia)/sizeof(int));
 50 
 51 
 52     show(ia);
 53 
 54     return EXIT_SUCCESS;
 55 }