How to sort an array without using sort method in Ruby?

Akashkinwad
2 min readJul 27, 2022

Many times we may come across a question like sorting an array without using sort methods available in ruby.
This blog will help you to sort the array without using the in build methods in ruby.

  1. Sort in Descending Order
def sort_descending(array)
return [] if array.empty?
is_sorted = true

while is_sorted
is_sorted = false

(array.size - 1).times do |i|
if array[i] < array[i + 1]
array[i], array[i + 1] = array[i + 1], array[i]
is_sorted = true
end
end
end
array
end

Explanation:

  1. Used while loop until array gets sorted
  2. Loop over the array for (array.size — 1) times
  3. If element is less than the next element, then swap the elements
  4. Continue loop until array gets sorted.

Usage

number_array = [57,2,30, 4, 1, 45, 8, 11]
char_array = ['d', 'v', 'r', 'f', 'b', 'a', 'p', 'x', 'z']
2.5.3 :361 > sort_descending(number_array)
=> [57, 45, 30, 11, 8, 4, 2, 1]

2.5.3 :362 > sort_descending(char_array)
=> ["z", "x", "v", "r", "p", "f", "d", "b", "a"]

2. Sort in Ascending Order

def sort_ascending(array)
return [] if array.empty?
is_sorted = true

while is_sorted
is_sorted = false

(array.size - 1).times do |i|
if array[i] > array[i + 1]
array[i], array[i + 1] = array[i + 1], array[i]
is_sorted = true
end
end
end
array
end

Usage

number_array = [57,2,30, 4, 1, 45, 8, 11]
char_array = ['d', 'v', 'r', 'f', 'b', 'a', 'p', 'x', 'z']
2.5.3 :361 > sort_ascending(number_array)
=> [1, 2, 4, 8, 11, 30, 45, 57]

2.5.3 :362 > sort_ascending(char_array)
=> ["a", "b", "d", "f", "p", "r", "v", "x", "z"]

--

--