I have this Algorithm that sorts array of integers implemented in a simple inventory system in Visual Basic 6.0 for my thesis. The system can sort items by total price, unit price, quantity, etc. But when the input number is within 7 or more digits (ex: 3,382,328), the application produces this error:

Run-time error '9':
Subscript out of range

I believe the problem occurs because the algorithm creates an array with the size equal to the largest input number (which is 3,382,328) that is why it produces an out of range error.
Is there anything that I can do with the algorithm or the programming language or the data type used? I used double as my data type. How do I solve it? If I stop creating arrays equal to the size of the largest input number, the algorithm will not be able to sort correctly. Here's the code where the error occurs:

``````Dim q, e, g As Integer
'parr(mini) = maxi
If mini <> maxi Then
If nop > 0 Then
For e = 0 To maxi + 1
'On Error GoTo hell
parri(e) = 0
'hell:
Next e
End If
If non > 0 Then
For g = 0 To Abs(mini) + 1
narr(g) = 0
Next g
End If
'distribution of data to respective array
For q = 1 To size
If Val(ListView2.ListItems(q).ListSubItems(… >= 0 Then
parri(ListView2.ListItems(q).ListSubItem… = Val(parri(ListView2.ListItems(q).ListSub… + 1
Else
narr(Abs(ListView2.ListItems(q).ListSubI… = Val(narr(Abs(ListView2.ListItems(q).List… + 1
End If
Next q
End If``````

the error occurs in

``parri(e) = 0``

where it creates an array called parri with the size of e where the current value of e is in millions. How do I fix this? Thanks.

Your sort routine is a variant of the Bucket sort. I'd pick a different sort routine that doesn't require extra storage space (Shell, Quick, Heap)

## All 4 Replies

Your sort routine is a variant of the Bucket sort. I'd pick a different sort routine that doesn't require extra storage space (Shell, Quick, Heap)

First, please format your code properly so we can follow it. All loops and ifs need to be indented:

``````Dim q, e, g As Integer
'parr(mini) = maxi
If mini <> maxi Then
If nop > 0 Then
For e = 0 To maxi + 1
'On Error GoTo hell
parri(e) = 0
'hell:
Next e
End If

If non > 0 Then
For g = 0 To Abs(mini) + 1
narr(g) = 0
Next g
End If``````

Next, assuming parri is defined to have maxi elements, your first loop goes beyond the limits:

``````For e = 0 To maxi + 1
parri(e) = 0
Next e``````

The length for an integer is limited, hence your error. Change integer to Long or to Double which allows for a much larger result.)