Exercises from Chapter 14

Rite of Passage: Sorting

(Found here.)

Write a sort method that takes an array and returns a sorted version of it.

How You Could Do It

1: def​ ​sort​(arr)
if​ arr.​length​ < 1
arr ​# an empty array is already sorted
else
5:  pivot = arr.​pop
smaller_elements = []
larger_elements = []
10:  arr.​each​ ​do​ |elem|
if​ elem < pivot
smaller_elements.​push​(elem)
else
larger_elements.​push​(elem)
15: end
end
smaller_sorted = sort(smaller_elements)
larger_sorted = sort(larger_elements )
20: 
smaller_sorted + [pivot] + larger_sorted
end
end
25: puts(sort([​"can"​,​"feel"​,​"singing"​,​"like"​,​"a"​,​"can"​]))
<= a
 can
 can
 feel
 like
 singing

How I Would ...

Get Learn to Program, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.