NOIDATUT FREE E LEARNING PLATFORM • AKTU B.TECH

Selection Sorting

Selection sort divides a list into sorted and unsorted parts, repeatedly finding the minimum (or maximum) element from the unsorted portion and swapping it into place. It runs in O(n²) time across best, average, and worst cases with O(1) space.


Theory & Explanation

Selection Sort: Definition, Stepwise Working, Complexity & Code

1. Definition & Key Characteristics

Selection Sort is an in-place comparison sorting algorithm that divides a list into two parts: a sorted subarray on the left (initially empty) and an unsorted subarray on the right (initially the entire list). In each pass, it finds the smallest (minimum) element in the unsorted subarray (for ascending order) and swaps it with the leftmost element of the unsorted subarray, expanding the sorted boundary by one position.

  • In-Place Sorting: Uses only a few index/temporary variables, requiring O(1) auxiliary space.
  • Minimizes Swaps: Performs at most n - 1 swaps in total (one per pass), unlike bubble sort which may swap on every adjacent comparison.
  • Not Stable (in Standard Swap): Swapping a minimum element with an earlier element can change the relative order of equal keys (for example, swapping 20a with a later 10 past 20b).
  • Input-Insensitive Comparisons: Always performs n(n - 1)/2 comparisons regardless of whether the array is already sorted, reverse-sorted, or random.

2. How Selection Sort Works (Step-by-Step Algorithm)

  1. Let the array have n elements at indices 0 to n - 1.
  2. Run an outer loop i from 0 to n - 2 (representing the boundary index where the next smallest element should be placed).
  3. Assume the minimum element is at index i: set minIdx = i.
  4. Scan the unsorted portion using an inner loop j from i + 1 to n - 1:
    • If arr[j] < arr[minIdx], update minIdx = j.
  5. After the inner loop finishes, if minIdx != i, swap arr[i] and arr[minIdx].
  6. Repeat until i reaches n - 2; the array is then completely sorted.

3. Step-by-Step Example & Graphical Representation

Sort arr = [40, 20, 30, 10] (n = 4) in ascending order:

  • Pass 1 (i = 0, search unsorted range 0..3):
    • Start with minIdx = 0 (value 40).
    • Compare with 20 (idx 1) → minIdx = 1; compare with 30 (idx 2) → keep 1; compare with 10 (idx 3) → minIdx = 3 (value 10).
    • Swap arr[0] (40) and arr[3] (10) → [10, 20, 30, 40]. Sorted prefix: [10].
  • Pass 2 (i = 1, search unsorted range 1..3):
    • Minimum in [20, 30, 40] is 20 at minIdx = 1.
    • minIdx == i, so no swap needed → [10, 20, 30, 40]. Sorted prefix: [10, 20].
  • Pass 3 (i = 2, search unsorted range 2..3):
    • Minimum in [30, 40] is 30 at minIdx = 2.
    • minIdx == i, so no swap needed → [10, 20, 30, 40]. Sorted prefix: [10, 20, 30] (and 40 is automatically in place).

Graphical Representation: Stepwise Passes of Selection Sort on [40, 20, 30, 10]

Selection Sort Pass-by-Pass Trace (Ascending): [40, 20, 30, 10] → [10, 20, 30, 40] Initial: 40 20 30 10 All elements initially unsorted Pass 1: 10 20 30 40 Min 10 swapped with index 0 (40) Pass 2: 10 20 30 40 Min 20 already at index 1 (no swap) Pass 3: 10 20 30 40 Min 30 at index 2; array sorted! Green = sorted left prefix | Amber = unsorted elements scanned to find minimum

4. Time & Space Complexity Analysis

Case Condition Comparisons Swaps Time Complexity
Best Case Array is already sorted n(n - 1)/2 0 O(n2)
Average Case Randomly ordered elements n(n - 1)/2 At most n - 1 O(n2)
Worst Case Array is sorted in reverse order n(n - 1)/2 At most n - 1 O(n2)

Auxiliary Space Complexity: O(1) (in-place sorting).

5. C Program: Selection Sort

#include <stdio.h>

void selectionSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int minIdx = i; // Assume current position holds the minimum
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIdx]) {
                minIdx = j; // Found a smaller element
            }
        }
        if (minIdx != i) {
            int temp = arr[i];
            arr[i] = arr[minIdx];
            arr[minIdx] = temp;
        }
    }
}

void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {40, 20, 30, 10};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("Original array: ");
    printArray(arr, n);

    selectionSort(arr, n);

    printf("Sorted array (Ascending): ");
    printArray(arr, n);

    return 0;
}

Expected Output (C):

Original array: 40 20 30 10 
Sorted array (Ascending): 10 20 30 40 

6. Python Program: Selection Sort

def selection_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        min_idx = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_idx]:
                min_idx = j
        if min_idx != i:
            arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr


if __name__ == "__main__":
    data = [40, 20, 30, 10]
    print("Original array:", data)
    sorted_data = selection_sort(data[:])
    print("Sorted array (Ascending):", sorted_data)

Expected Output (Python):

Original array: [40, 20, 30, 10]
Sorted array (Ascending): [10, 20, 30, 40]
Advertisement
Advertisement