I am using AlgoBuild to make a program that sorts numbers.
This is my attempt:
AlgoBuild translates this chart to the following pseudo code:
PROGRAM main
INPUT int D
FOR i = 0; i < D; i = i + 1
INPUT V[i]
END FOR
FOR i = 1; i <= D; i = i + 1
k = i
FOR j = i + 1; j <= D; j = j + 1
IF V[k] > V[j]
k = j
END IF
END FOR
IF i != k
temp = V[i]
V[i] = V[k]
V[k] = temp
END IF
END FOR
FOR i = 0; i < D; i = i + 1
OUTLN V[i]
END FOR
END
When running it, I got the following error on the statement IF V[k] > V[j]
:
IF ERROR: Array index out of range IN V[k] > V[j]
I didn't expect this error.
I can't understand why it is out of range if I made the assignment k
is equal to j
. What is my mistake?
Your second and third loop allow their loop variables to become equal to D
, but you have not defined V[D]
, so that will be out of range.
Array indices run from 0 onwards, so if you have D
number of values in your array V
, the first one is V[0]
and the last one is V[D-1]
, not V[D]
.
So change <= D
in your middle loops to < D
, like this:
i = 0; i < D; i = i + 1
and
j = i + 1; j < D; j = j + 1
With those two fixes it works.