DSA Tutorial



SELECTION SORT


🧠 Selection Sort in DSA

Selection Sort is a simple and intuitive comparison-based sorting algorithm. It repeatedly selects the minimum (or maximum) element from the unsorted part and places it at the beginning.

šŸŽÆ Imagine a race where you pick the slowest runner and put them in front one by one!

āš™ļø How It Works

  1. Start from index 0 and find the smallest element.
  2. Swap it with the element at index 0.
  3. Repeat the process for the rest of the array.

šŸ“Œ Example

Initial Array: [29, 10, 14, 37, 14]

  • Smallest is 10 → Swap with 29 → [10, 29, 14, 37, 14]
  • Next smallest is 14 → Swap with 29 → [10, 14, 29, 37, 14]
  • Next smallest is 14 → Swap with 29 → [10, 14, 14, 37, 29]
  • Swap 29 and 37 → [10, 14, 14, 29, 37]

šŸ’» C Code Example

#include <stdio.h>

void selectionSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int minIndex = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        // Swap
        int temp = arr[minIndex];
        arr[minIndex] = arr[i];
        arr[i] = temp;
    }
}

int main() {
    int a[] = {29, 10, 14, 37, 14};
    int n = 5;
    selectionSort(a, n);
    for (int i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    return 0;
}
    
ā±ļø Time Complexity: O(n²) in all cases
šŸš€ Space Complexity: O(1) — No extra space used
šŸ’” Selection Sort is not very efficient on large lists, but its simplicity makes it useful in teaching and small-scale scenarios.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review