Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@
| 652 | Find Duplicate Subtrees | [Ruby](./algorithms/ruby/0652-find-duplicate-subtrees.rb) | Medium |
| 733 | Flood Fill | [Ruby](./algorithms/ruby/0733-flood-fill.rb) | Easy |
| 783 | Minimum Distance Between BST Nodes | [Ruby](./algorithms/ruby/0783-minimum-distance-between-bst-nodes.rb) [Python3](./algorithms/python3/0783-minimum-distance-between-bst-nodes.py) | Easy |
| 904 | Fruit Into Baskets | [Ruby](./algorithms/ruby/0904-fruit-into-baskets:description.rb) | Medium |
| 904 | Fruit Into Baskets | [Ruby](./algorithms/ruby/0904-fruit-into-baskets.rb) | Medium |
| 912 | Sort an Array | [Ruby](./algorithms/ruby/0912-sort-an-array.rb) | Medium |
| 953 | Verifying an Alien Dictionary | [Ruby](./algorithms/ruby/0953-verifying-an-alien-dictionary.rb) | Easy |
| 989 | Add to Array-Form of Integer | [Ruby](./algorithms/ruby/0989-add-to-array-form-of-integer.rb) | Easy |
| 990 | Satisfiability of Equality Equations | [Ruby](./algorithms/ruby/0990-satisfiability-of-equality-equations.rb) | Medium |
Expand Down
50 changes: 50 additions & 0 deletions algorithms/ruby/0912-sort-an-array.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# frozen_string_literal: true

# Problem: 912. Sort an Array
# URL: https://leetcode.com/problems/sort-an-array

# @param {Integer[]} nums
# @return {Integer[]}
def sort_array(nums)
in_place_quick_sort(nums, 0, nums.length - 1)
nums
end

def in_place_quick_sort(nums, l, r)
return if l >= r

pivot = nums[rand(l..r)]
pl, pr = partition(nums, l, r, pivot)
in_place_quick_sort(nums, l, pl - 1)
in_place_quick_sort(nums, pr + 1, r)
end

def partition(nums, l, r, pivot)
p0, p1, p2 = l, l, r
while p1 <= p2
if nums[p1] < pivot
nums[p0], nums[p1] = nums[p1], nums[p0]
p0 += 1
p1 += 1
elsif nums[p1] == pivot
p1 += 1
else
nums[p1], nums[p2] = nums[p2], nums[p1]
p2 -= 1
end
end

[p0, p2]
end

# ********************#
# TEST #
# ********************#

require "test/unit"
class Test_sort_array < Test::Unit::TestCase
def test_
assert_equal [1, 2, 3, 5], sort_array([5, 2, 3, 1])
assert_equal [0, 0, 1, 1, 2, 5], sort_array([5, 1, 1, 2, 0, 0])
end
end