Array sorting and reversing in Ruby - Time & Space Complexity
When we sort or reverse an array, we want to know how the time it takes changes as the array gets bigger.
We ask: How does the work grow when the array size grows?
Analyze the time complexity of the following code snippet.
arr = [5, 3, 8, 1, 2]
sorted_arr = arr.sort
reversed_arr = sorted_arr.reverse
puts reversed_arr
This code sorts an array and then reverses the sorted array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorting the array (arr.sort) which compares and rearranges elements.
- How many times: Sorting usually looks at many pairs of elements multiple times depending on the algorithm.
- Secondary operation: Reversing the array (arr.reverse) which swaps elements from start to end once.
- How many times: Reversing goes through the array once, swapping pairs.
Sorting takes more time as the array grows, much more than just going through it once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 to 40 comparisons and swaps |
| 100 | About 700 to 1000 comparisons and swaps |
| 1000 | About 10,000 to 15,000 comparisons and swaps |
Pattern observation: Sorting grows faster than the size itself, roughly like n times log n. Reversing grows just like the size.
Time Complexity: O(n log n)
This means sorting takes more time as the array grows, but reversing only adds a small extra step.
[X] Wrong: "Sorting and reversing both take the same time because they both touch every element."
[OK] Correct: Reversing just swaps elements once, so it grows linearly. Sorting compares many pairs multiple times, so it grows faster than just the number of elements.
Understanding how sorting and reversing scale helps you explain your code choices clearly and shows you know what happens behind the scenes.
"What if we used a different sorting method that is already optimized for nearly sorted arrays? How would the time complexity change?"
Practice
sort do when called on an array?Solution
Step 1: Understand the purpose of
Thesortsortmethod arranges elements in ascending order by default.Step 2: Compare with other methods
Unlikereversewhich flips order,sortorders elements from smallest to largest.Final Answer:
It arranges the elements in ascending order. -> Option AQuick Check:
sort = ascending order [OK]
- Confusing sort with reverse
- Thinking sort removes duplicates
- Assuming sort shuffles elements
arr in Ruby?Solution
Step 1: Identify the correct method call
The method to reverse an array in place isreverse!called on the array object.Step 2: Check syntax correctness
Onlyarr.reverse!is valid Ruby syntax; others are incorrect method calls or misplaced symbols.Final Answer:
arr.reverse! -> Option AQuick Check:
reverse! modifies array in place [OK]
reverse! to reverse array in place [OK]- Using parentheses incorrectly
- Placing exclamation mark after parentheses
- Calling reverse as a standalone function
arr = [3, 1, 4, 2] sorted_arr = arr.sort reversed_arr = sorted_arr.reverse puts reversed_arr.inspect
Solution
Step 1: Sort the original array
Callingarr.sortreturns a new array sorted ascending: [1, 2, 3, 4].Step 2: Reverse the sorted array
Callingsorted_arr.reverseflips the order to [4, 3, 2, 1].Final Answer:
[4, 3, 2, 1] -> Option CQuick Check:
sort then reverse = descending order [OK]
- Assuming reverse modifies original array
- Confusing sorted array with original
- Expecting reverse to sort ascending
arr = [5, 2, 9] arr.sort! arr.reverse puts arr.inspect
Solution
Step 1: Understand
sort!effectsort!sorts the arrayarrin place, soarrbecomes [2, 5, 9].Step 2: Check
reversemethod usagereversereturns a new reversed array but does not modifyarritself.Final Answer:
Usingreversedoes not changearrin place. -> Option DQuick Check:
reverse without ! returns new array [OK]
reverse! to modify array in place [OK]- Assuming reverse changes original array
- Thinking sort! is invalid
- Believing method calls need parentheses always
arr = [7, 3, 5, 3, 9, 1], how can you create a new array that is sorted in descending order without changing the original array?Solution
Step 1: Sort the array without modifying original
arr.sortreturns a new sorted array ascending, originalarrstays unchanged.Step 2: Reverse the sorted array to get descending order
Callingreverseon the sorted array returns a new array reversed, still not changing original.Final Answer:
Usearr.sort.reverse-> Option BQuick Check:
sort then reverse = descending new array [OK]
- Using sort! or reverse! which modify original array
- Reversing before sorting
- Expecting reverse.sort to work the same
Ready to prove it?
Pass the test and this pattern moves unknown
