Ruby Program to Perform Selection Sort on an Array
for i in 0...arr.length; min_idx = i; for j in i+1...arr.length; min_idx = j if arr[j] < arr[min_idx]; end; arr[i], arr[min_idx] = arr[min_idx], arr[i]; end.Examples
How to Think About It
Algorithm
Code
def selection_sort(arr) n = arr.length for i in 0...n min_idx = i for j in (i + 1)...n min_idx = j if arr[j] < arr[min_idx] end arr[i], arr[min_idx] = arr[min_idx], arr[i] end arr end puts selection_sort([3, 1, 4, 2]).inspect
Dry Run
Let's trace [3, 1, 4, 2] through the code
Initial array
[3, 1, 4, 2]
Find smallest from index 0
Smallest is 1 at index 1, swap with 3
Array after first swap
[1, 3, 4, 2]
Find smallest from index 1
Smallest is 2 at index 3, swap with 3
Array after second swap
[1, 2, 4, 3]
Find smallest from index 2
Smallest is 3 at index 3, swap with 4
Array after third swap
[1, 2, 3, 4]
Index 3 is last, done
[1, 2, 3, 4]
| Iteration | Current Index (i) | Min Index (min_idx) | Array State |
|---|---|---|---|
| 1 | 0 | 1 | [1, 3, 4, 2] |
| 2 | 1 | 3 | [1, 2, 4, 3] |
| 3 | 2 | 3 | [1, 2, 3, 4] |
Why This Works
Step 1: Find minimum element
The inner loop finds the smallest element in the unsorted part by comparing each element with the current minimum using <.
Step 2: Swap elements
After finding the smallest element, it swaps places with the element at the current position using parallel assignment arr[i], arr[min_idx] = arr[min_idx], arr[i].
Step 3: Repeat for all positions
The outer loop moves the current position forward, repeating the process until the entire array is sorted.
Alternative Approaches
arr = [3, 1, 4, 2] puts arr.sort.inspect
def recursive_selection_sort(arr, start=0) return arr if start >= arr.length - 1 min_idx = start (start + 1...arr.length).each do |i| min_idx = i if arr[i] < arr[min_idx] end arr[start], arr[min_idx] = arr[min_idx], arr[start] recursive_selection_sort(arr, start + 1) end puts recursive_selection_sort([3, 1, 4, 2]).inspect
Complexity: O(n^2) time, O(1) space
Time Complexity
Selection sort uses two nested loops each running up to n times, so it takes about n squared steps, or O(n^2).
Space Complexity
It sorts the array in place without extra memory, so space complexity is O(1).
Which Approach is Fastest?
Using Ruby's built-in sort is fastest and recommended for real use, but selection sort helps understand sorting basics.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Selection Sort | O(n^2) | O(1) | Learning sorting basics |
| Recursive Selection Sort | O(n^2) | O(n) due to recursion stack | Understanding recursion |
| Ruby Built-in sort | O(n log n) | O(n) | Practical sorting tasks |