0
0
RubyProgramBeginner · 2 min read

Ruby Program to Sort Array with Example and Explanation

In Ruby, you can sort an array using the sort method like this: sorted_array = array.sort, which returns a new array sorted in ascending order.
📋

Examples

Input[3, 1, 2]
Output[1, 2, 3]
Input[10, 5, 8, 1]
Output[1, 5, 8, 10]
Input[]
Output[]
🧠

How to Think About It

To sort an array, think about arranging its elements from smallest to largest. Ruby provides a simple way to do this by comparing each element and placing them in order using the sort method, which handles the comparisons and rearrangements automatically.
📐

Algorithm

1
Get the input array.
2
Use the built-in sort method to arrange elements in ascending order.
3
Return or print the sorted array.
💻

Code

ruby
array = [3, 1, 2, 5, 4]
sorted_array = array.sort
puts sorted_array.inspect
Output
[1, 2, 3, 4, 5]
🔍

Dry Run

Let's trace sorting the array [3, 1, 2, 5, 4] through the code

1

Initial array

array = [3, 1, 2, 5, 4]

2

Call sort method

sorted_array = array.sort

3

Sorted result

sorted_array = [1, 2, 3, 4, 5]

4

Print sorted array

puts sorted_array.inspect outputs [1, 2, 3, 4, 5]

StepArray State
Initial[3, 1, 2, 5, 4]
After sort[1, 2, 3, 4, 5]
💡

Why This Works

Step 1: Using the sort method

The sort method compares elements and arranges them from smallest to largest automatically.

Step 2: Returns a new array

sort does not change the original array but returns a new sorted array.

Step 3: Printing the result

Using puts sorted_array.inspect shows the sorted array clearly in the output.

🔄

Alternative Approaches

sort! method
ruby
array = [3, 1, 2, 5, 4]
array.sort!
puts array.inspect
This method sorts the array in place, changing the original array instead of creating a new one.
Custom sort with block
ruby
array = [3, 1, 2, 5, 4]
sorted_array = array.sort { |a, b| b <=> a }
puts sorted_array.inspect
This sorts the array in descending order by providing a block to the sort method.

Complexity: O(n log n) time, O(n) space

Time Complexity

Ruby's sort uses a quicksort or mergesort algorithm internally, which runs in O(n log n) time for n elements.

Space Complexity

sort creates a new array, so it uses O(n) extra space, while sort! sorts in place using less extra memory.

Which Approach is Fastest?

sort! is faster in memory use since it sorts in place, but both have similar time complexity.

ApproachTimeSpaceBest For
sortO(n log n)O(n)When you want to keep the original array unchanged
sort!O(n log n)O(1)When you want to sort the original array directly
sort with blockO(n log n)O(n)Custom sorting order like descending
💡
Use sort for a new sorted array and sort! to sort the original array directly.
⚠️
Beginners often forget that sort returns a new array and does not change the original array unless sort! is used.