Alphabetical Order

tags: character-comparison array-traversal

Check if an array of strings is in alphabetical order.

Implementation

The current character can be compared with the preceding character:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def alphabetical?(s)
  n = s.size
  
  for i in (1..n-1)
    if s[i-1] > s[i]
      return false
    end 
  end
  
  return true
end

In the implementation the starting index is 1 and the ending index is n-1. The current characters can be compared with the next character:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def alphabetical?(s)
  n = s.size
  
  for i in (0..n-2)
    if s[i] > s[i+1]
      return false
    end 
  end
  
  return true
end

In this alternative implementation the starting index is 0 and the end index is n-2. In Ruby both the implementations work for string as well as array input.