Go back

Data Structures and Algorithms - Selection Sort - Day 5

About selection sort

We go through the array and select the lowest element and swap it with the highest element. Then we take the array from index 1 and keep doing the same thing until the end of the array is reached.

Code

#include<stdio.h>

int main() {
    int n;

    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);

    int arr[n];
    printf("Enter %d elements: ", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    int i, j, k, temp;

    //n-1 because we don't need to swap the last element with itself;
    for (i = 0; i < n - 1; i++) {
        k = i;
        for (j = i; j < n; j++) {
            if (arr[j] < arr[k]) {
                k = j;
            }
        }
        if (k != i) {
            // swap arr[i] and arr[k]
            temp = arr[i];
            arr[i] = arr[k];
            arr[k] = temp;
        }
        //use this loop to see intermediate steps
        for (int k = 0; k < n; k++)
            printf("%d ", arr[k]);
        printf("\n");
    }

    printf("Sorted array: \n");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");

    return 0;
}

Complexity

Time Complexity - O(n^2) for all the cases.