Selection Sort
🌟 Selection Sort
Selection Sort is a simple sorting algorithm.
It works by repeatedly finding the minimum (or maximum) element from the unsorted part of the array and moving it to the beginning.
✏️ How Selection Sort works step-by-step:
-
Start with the first element of the array.
-
Find the smallest element in the array.
-
Swap it with the first element.
-
Move to the second position, and repeat the process for the remaining elements.
-
Continue until the entire array is sorted.
Selection Sort Algorithm
Input: An array arr[]
of size n
Output: Sorted array in ascending order
🔥 Let's Break it Down:
-
Outer loop (
i
): For each position in the array. -
Inner loop (
j
): Find the smallest element in the unsorted part. -
Swap the smallest found with the current
i
th element.
📜 Simple Example
Suppose the array is:
arr = [64, 25, 12, 22, 11]
Steps:
-
Find the minimum from index 0 to 4 → 11 → Swap 11 and 64 →
[11, 25, 12, 22, 64]
-
Find the minimum from index 1 to 4 → 12 → Swap 12 and 25 →
[11, 12, 25, 22, 64]
-
Find the minimum from index 2 to 4 → 22 → Swap 22 and 25 →
[11, 12, 22, 25, 64]
-
Find the minimum from index 3 to 4 → 25 already minimum → No swap
-
Last element is automatically sorted.
Final sorted array: [11, 12, 22, 25, 64]
✅ Key Points
-
Time Complexity:
-
Best Case: O(n²)
-
Average Case: O(n²)
-
Worst Case: O(n²)
-
-
Space Complexity: O(1) (In-place sorting)
-
Stability: ❌ Not stable (unless modified carefully)
-
Useful: When memory is very limited.
Comments
Post a Comment