0

I am using AlgoBuild to make a program that sorts numbers.

This is my attempt:

enter image description here

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?

2
  • 3
    "if I don't write some more lines it won't make me post the question" - never just write waffle in order to satisfy a quality filter. Instead, think about what would actually provide more useful information... such as the size of the array, and the precise error message you're seeing. (I'm not familiar with matlab, but does the error tell you which of the steps is failing, for example?) I'd be astonished if there was really nothing else you could add to the question that would provide useful information.
    – Jon Skeet
    Commented Jul 8 at 17:30
  • I'm kinda new to this and I was in a hurry, next time I will add more detail. Thanks for the answer btw
    – giuamato50
    Commented Jul 9 at 0:23

1 Answer 1

1

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.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.