[Gambas-user] WHILE and AND: please explain me....
Benoît Minisini
gambas at ...1...
Wed May 5 01:20:23 CEST 2010
> I'm working with this little piece of code, it's the Insertion Sort:
>
> PUBLIC SUB InsertionSort(matrix AS String[])
> DIM i, j AS Integer
> DIM x AS String
>
> FOR i = 1 TO (matrix.Count - 1)
> x = matrix[i]
> j = i - 1
> WHILE j >= 0 AND matrix[j] > x
> matrix[j + 1] = matrix[j]
> j -= 1
> WEND
> matrix[j + 1] = x
> NEXT
> END
>
> But I get an "Out of bound" error in the WHILE test, because j begins
> -1.
>
> Usually (in other languages this is the behavior) the AND test checks
> the first condition, and if it is false then it checks the second one.
> OK... but shouldn't Gambas bypass the WHILE statement because j is
> negative?
AND is a logical operator in Gambas, and it evaluates both of its arguments.
You must write it this way:
DO
IF j < 0 OR IF matrix[j] <= x THEN BREAK
matrix[j + 1] = matrix[j]
j -= 1
LOOP
Regards,
--
Benoît Minisini
More information about the User
mailing list