How to sort an array with a single loop in Ruby

1 Answer

0 votes
# Sorts an array in-place in non-decreasing order using Gnome Sort.
#
# Algorithm Logic (Single Loop):
# - Advances through the array using a single while loop index.
# - Moves forward when adjacent elements are in correct relative order.
# - When an out-of-order adjacent pair is encountered, swaps the elements
#   and steps backward one index to verify order against preceding items.
# - Time Complexity: O(N) best case (already sorted), O(N^2) worst case.
# - Space Complexity: O(1) auxiliary space.
#
# @param arr [Array<Comparable>] The mutable array to be sorted in place.
# @return [Array<Comparable>] The same array reference, sorted.
def single_loop_sort!(arr)
  pos = 0
  len = arr.length

  while pos < len
    # Move forward if at index 0 or if adjacent pair is in correct order
    if pos.zero? || arr[pos] >= arr[pos - 1]
      pos += 1
    else
      # Swap adjacent out-of-order elements using parallel assignment
      arr[pos], arr[pos - 1] = arr[pos - 1], arr[pos]
      pos -= 1
    end
  end

  arr
end

# Main
def main
  numbers = [42, -5, 12, 0, 89, -18, 33, 7]

  puts 'Original array:'
  puts numbers.join(' ')

  single_loop_sort!(numbers)

  puts "\nSorted array:"
  puts numbers.join(' ')
end

main if __FILE__ == $PROGRAM_NAME


# run:
#
# Original array:
# 42 -5 12 0 89 -18 33 7
#
# Sorted array:
# -18 -5 0 7 12 33 42 89
#

 



answered Aug 8 by avibootz
...