squares[] and sorting vertices into arrays...

I was working on a physics function which works by setting the player's height to the value of the nearest item in an array to the player's x and z. So if the player's x was 10 and z was 10, then the player's y would be squares[10][10].

I have a rough approximate function which performs the actual finding in squares[x][y], but the problem is in the function which runs once at the start of the app, which sorts the terrain's verts into squares[160][160].

I have two main ways to do this:

- Pick a vertex and scroll through the squares[160][160] until the most appropriate item is found.

- Pick an item and scroll through the verts making an average of all verts found.

The pick a vertex method takes too long, and then crashes the program when finished.
Here's my function:

and it will start to actually tell you something helpful about what is going on.
Then have a careful look at what is going on in that while loop - the "or nothing equals 0" bit looks like a recipe for a bounds overflow to me. Maybe there's a way to re-factor things into nested for loops as that makes it much easier to be sure nothing will overflow.