Monday, September 27, 2010

Is Sorted?

Given an array arr that consists of a series of elements, to determine whether the array is sorted the following algorithm can be used.

1. Begin iterating through the array from the first element to the second to last
2. Compare each element to the next one in the array based on whatever criteria you are using to determine order (i.e. greatest to least...)
3. As soon as you find a pair that is not in order (i.e. the greater value is on the left) return false
4. If you finish all the comparisons, your array is sorted.

Here's a sample program written in Python that determines if any list of numbers is sorted by ascending value:

for x in range(len(arr) - 1):
if arr.get(x+1) < arr.get(x):
return false
return true

Regardless of how the numbers are organized or arranged in the list, this algorithm will always be able to tell if the list is sorted, and at most this algorithm makes n-1 comparisons.

1 comment:

  1. I know this is late.... but I felt guilty and though I thought I should do this anyway. Sorry!

    ReplyDelete