Sebastian Hungerecker
7/19/2007 9:11:00 AM
johny.lam wrote:
> if (unsorted_array[i+1] != nil) and (unsorted_array[i] <
> unsorted_array[i+1])
> unsorted_array[i], unsorted_array[i+1] = unsorted_array[i+1],
> unsorted_array[i]
> end
> [...]
> what i don't get is that this program sorts the words into reverse
> alphabetical order.
Ok, let's look at what the above code does: It looks at an item in the array
(unsorted_array[i]) and at the one after it (unsorted_array[i+1]). Then it
checks whether the item is less than the next one and if so, it switches them.
Ultimately this will result in an array in which every element is more than
the element after it, i.e. an array sorted in descending order.
> but if i switch the less than sign in "if (unsorted_array[i+1] != nil)
> and (unsorted_array[i] < unsorted_array[i+1])" to a greater than sign
> the program works correctly.
Yes, because then it will switch the two items if the current item is more
than the next one, which will result in an array in which every element is
less than the next, i.e. an array sorted in ascending order, which is what
you want.
> what i am trying to is move the smallest word into the sorted_array
> but if i use the greater than sign wouldn't the move the biggest word
> into the sorted_array?
The code doesn't create a new array. It just switches the items in the array
around untill the array is sorted. Of course the items should only be switched
if they are not already in the right order. So you check whether the items are
in the wrong order (i.e. whether the current item is more than the next one)
and if so, switch the items.
HTH,
Sebastian
--
Ist so, weil ist so
Bleibt so, weil war so