Egbert Lin's Blog

“Life is not a race, but a journey to be savoured each step of the way” by Brian Dyson

Data Structures - Selection Sort

Basic programming - Selection Sort

Approach:

Declare two variables, i likes the end pointer of sorted vector and j likes the scanning pointer.

Aims to find the smallest value (or biggest value), therefore, j starts from i to scan until the end of nums. Then, the smallest value is changed with the value of index i by calling swap(). It means adding the smallest value to the sorted vector. Next step, i moves to the next index and go back to the previous action until all values are sorted.

Time complexity:
  • Best Case:Ο(n2)
  • Worst Case:Ο(n2)
  • Average Case:Ο(n2)
  • P.S. Whatever the input is, there are two for-loop to run!

    Space complexity: O(1)

    Stable/Unstable: Unstable

    Source code

    Version 1

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    #include <iostream>
    #include <vector>
    #include <climits>

    using namespace std;

    void swap(int& l, int& r){
    int temp = l;
    l = r;
    r = temp;
    }

    vector<int> selectSort(vector<int>& nums){
    const int n = nums.size();
    for(int i = 0; i < n; i++){
    int min_value = INT_MAX;
    int pos = 0;
    for(int j = i; j < n; j++){
    if(nums[j] < min_value){
    min_value = nums[j];
    pos = j;
    }
    }
    if(pos != i){
    swap(nums[i], nums[pos]);
    }
    }
    return nums;
    };

    int main()
    {
    vector<int> input{51,96,6,68,36,27,55,6,56,16};
    vector<int> sortedAns = selectSort(input);

    for(int i = 0; i < sortedAns.size(); i++){
    cout << sortedAns[i] << " ";
    }

    return 0;
    }