Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

Selection Sort Algorithm

Selection Sort

Code

void selectionSort(vector<int>& a, int n)
{
    for (int i = 0; i < n - 1; i++) { // till n-1
        int minIndex = i;
        for (int j = i + 1; j < n; j++) {
            if (a[j] < a[minIndex]) {
                minIndex = j;
            }
        }
        swap(a[i], a[minIndex]);
    }
}

Stable Selection Sort

Code

void stableSelectionSort(vector<int>& v, int n)
{
    int minIndex = 0;
    for (int i = 0; i < n - 1; i++) {
        minIndex = i;
        for (int j = i + 1; j < n; j++) {
            if (v[j] < v[minIndex]) {
                minIndex = j;
            }
        }
        // Move minimum element at current i
        int minElement = v[minIndex];
        while (minIndex > i) {
            v[minIndex] = v[minIndex - 1];
            minIndex--;
        }
        v[minIndex] = minElement;
    }
}

Analysis

References