Ruby Program to Implement Selection Sort

Ruby Program to Implement Selection Sort

Sorting is a fundamental concept in programming. Whenever you work with lists of data, arranging them in order can make it easier to analyze, search, or display. One of the simplest and most intuitive sorting algorithms is Selection Sort. It works by repeatedly finding the smallest (or largest) element from the unsorted portion of the array and placing it at the correct position. This step-by-step approach helps beginners understand how sorting algorithms organize data logically.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Selection Sort may not be the fastest algorithm for very large datasets, but its simplicity makes it perfect for learning. By implementing it in Ruby, a language known for its readable syntax, beginners can see clearly how data moves and changes. In this article, we will explore multiple ways to implement Selection Sort in Ruby, including using loops, recursion, and sorting in both ascending and descending orders. This will give you a solid foundation to understand other sorting algorithms in the future.

Program 1: Selection Sort Using Simple Loops

This first program demonstrates Selection Sort using straightforward for loops. It sorts a predefined array of numbers in ascending order.

# Program 1: Selection Sort using simple loops
numbers = [64, 25, 12, 22, 11]

n = numbers.length

for i in 0...(n - 1)

  min_index = i

  for j in (i + 1)...n

    if numbers[j] < numbers[min_index]
      min_index = j
    end

  end

  numbers[i], numbers[min_index] = numbers[min_index], numbers[i]

end

puts "Sorted array: #{numbers}"

In this program, the outer loop goes through each element and assumes it is the smallest. The inner loop then checks the rest of the array to find if there is a smaller element. If a smaller element is found, it swaps with the current position. Beginners can easily visualize how the smallest element moves to its correct position in each pass, making it simple to understand and apply.

Program 2: Selection Sort in Descending Order

While ascending order is common, you may sometimes want to sort data from largest to smallest. This program modifies the logic to achieve that.

# Program 2: Selection Sort in descending order
numbers = [30, 10, 50, 20, 40]
n = numbers.length

for i in 0...(n - 1)

  max_index = i

  for j in (i + 1)...n

    if numbers[j] > numbers[max_index]
      max_index = j
    end

  end

  numbers[i], numbers[max_index] = numbers[max_index], numbers[i]

end

puts "Sorted array (descending): #{numbers}"

Here, the program finds the largest element in each pass instead of the smallest. This teaches beginners how small changes in logic can produce different outcomes. Sorting in descending order is useful for scenarios like ranking scores, prioritizing tasks, or organizing lists based on importance.

Program 3: Selection Sort Using While Loops

You can also implement Selection Sort using while loops. This approach introduces beginners to alternative loop structures in Ruby while achieving the same sorting result.

# Program 3: Selection Sort using while loops
numbers = [45, 22, 89, 11, 33]
n = numbers.length
i = 0

while i < n - 1

  min_index = i
  j = i + 1

  while j < n

    if numbers[j] < numbers[min_index]
      min_index = j
    end

    j += 1

  end

  numbers[i], numbers[min_index] = numbers[min_index], numbers[i]

  i += 1

end

puts "Sorted array: #{numbers}"

This program works similarly to the for loop version, but the control is handled with while loops. Beginners can see how loops in Ruby can be flexible and learn to apply different structures depending on the situation. It also reinforces understanding of the selection process and swapping mechanism.

Program 4: Selection Sort Using Recursion

Recursion is a powerful concept where a function calls itself to solve smaller portions of a problem. Selection Sort can also be implemented recursively.

# Program 4: Selection Sort using recursion
def selection_sort_recursive(array, start = 0)

  return array if start >= array.length - 1

  min_index = start

  (start + 1...array.length).each do |i|
    min_index = i if array[i] < array[min_index]
  end

  array[start], array[min_index] = array[min_index], array[start]

  selection_sort_recursive(array, start + 1)

end

numbers = [29, 10, 14, 37, 13]
sorted_array = selection_sort_recursive(numbers)

puts "Sorted array: #{sorted_array}"

In this recursive approach, the algorithm finds the smallest element and places it at the start, then calls itself on the remaining unsorted portion. Recursion can feel tricky for beginners at first, but this example shows that the logic of Selection Sort naturally fits into a self-repeating process. Understanding recursion opens doors to solving many other problems in programming.

Frequently Asked Questions (FAQ)

Selection Sort often raises questions among beginners. Here are some common queries:

Q1: What is the time complexity of Selection Sort?
Selection Sort has a time complexity of O(n²) for all cases because it always scans the unsorted portion to find the smallest element. It is simple but not the fastest for large datasets.

Q2: Is Selection Sort stable?
By default, Selection Sort is not stable because it may change the relative order of equal elements during swapping. However, there are variations that can make it stable.

Q3: Can Selection Sort be used on strings?
Yes, Selection Sort can sort strings alphabetically. The comparison simply checks which string comes first in alphabetical order.

Q4: When should I use Selection Sort?
Selection Sort is suitable for small datasets or when learning sorting algorithms. For larger or performance-critical datasets, more efficient algorithms like Merge Sort or Quick Sort are recommended.

Conclusion

In this article, we explored how to implement Selection Sort in Ruby using multiple approaches, including simple loops, descending order sorting, while loops, and recursion. Selection Sort helps beginners understand the logic of finding the smallest or largest element and organizing an array step by step. By practicing these examples, you will strengthen your Ruby programming skills and develop a foundation to tackle more complex sorting algorithms in the future. Sorting doesn’t have to be intimidating, and with a bit of practice, it becomes a fun and intuitive part of programming.

Scroll to Top