in reply to Check this code please?

The first, important, thing would be to describe how the program behaves, and how that is not what you want. Having a clear image of what goes wrong may already point you towards the solution. If it does not point you towards the solution, at least you can now easily tell others what you think is wrong with your program. Supplying sample data also is important to demonstrate how your program behaves, and how it should behave.

The second, important, thing would be to use strict; and use warnings; at the top of your program. You have some variables that you only use once. This might be a typo. use warnings; will warn you about such situations. use strict; will force you to predeclare all your variables, so that mistyped names get prevented.

Also, have you looked at the sort built-in?

Consider the following input as an additional test case:

10000 2000 300 40 5