How to use Custom Sorting Algorithm In Ruby
This method implements a custom sorting algorithm to sort the characters of the string str
.
Example:
In this example, the input string “geekforgeeks” is iterated multiple times until the string is sorted.
# Define a method to sort a string's characters
# alphabetically using a custom sorting algorithm.
def sort_string(str)
# Get the length of the input string.
str_length = str.length
# Initialize a variable to track whether
# the string is sorted.
sorted = false
# Continue iterating until the string is sorted.
until sorted
# Assume the string is sorted initially.
sorted = true
# Iterate through the characters of the string.
(str_length - 1).times do |i|
# Compare adjacent characters.
if str[i] > str[i + 1]
# If the current character is greater than
# the next one, swap them.
str[i], str[i + 1] = str[i + 1], str[i]
# Since a swap was made, the string is not yet sorted.
sorted = false
end
end
end
# Return the sorted string.
str
end
# Example string to be sorted.
example_string = "geekforgeeks"
# Call the method to sort the example string
# and print the result.
puts sort_string(example_string)
Output
eeeefggkkors
How to Sort a String Characters Alphabetically in Ruby?
This article focuses on discussing how to sort a string’s characters alphabetically in Ruby.