0

I'm tearing my hair our trying to understand why the following insertion sort program in TI-BASIC works sometimes but gives a dimension error other times.

0→dim(L₁  // clear the list L1
randIntNoRep(1,5,5)→L₁
For(I,2,5)
L₁(I)→K
I-1→J
While J>0 and L₁(J)>K
L₁(J)→L₁(J+1)
J-1→J
End  // end while
K→L₁(J+1)
End  // end for
Disp L₁

As far as I can tell the code is a faithful implementation of Insertion Sort based on this pseudocode:

for i ← 2 to n
    key ← A[i]
    j ← i − 1
    while j > 0 and A[j] > key do
        A[j + 1] ← A[j]
        j ← j − 1
    A[j + 1] ← key

I've tried stepping through the code manually and it looks like the BASIC version does the same as the pseudocode. What am I missing please?

Robin Andrews
  • 3,514
  • 11
  • 43
  • 111

1 Answers1

0

OK I see the problem. TI-BASIC doesn't appear to do short circuit Boolean evaluation, so it sometimes tries to access the list at index 0, and fails. Refactoring in TI-BASIC is a real pain as there isn't even a break statement.

Robin Andrews
  • 3,514
  • 11
  • 43
  • 111