Last active
December 18, 2023 14:05
-
-
Save DmitryBash/e99cffcf17e2c09cd7c2e51a3028fe36 to your computer and use it in GitHub Desktop.
reverse array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def reverse_array(arr) | |
return arr if arr.empty? | |
arr = arr.dup | |
start_index = 0 | |
end_index = arr.length - 1 | |
while start_index < end_index | |
arr[start_index], arr[end_index] = arr[end_index], arr[start_index] | |
start_index += 1 | |
end_index -= 1 | |
end | |
arr | |
end | |
origin_array = [1, 2, 3, 4] | |
reverse_array(origin_array) # => [4, 3, 2, 1] | |
reverse_array([]) # => [] | |
origin_array # => [1, 2, 3, 4] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment