Suppose there is an arrayA
containing negative numbers, zero and positive numbers. You need to sort them, how would you do it. Ofcourse you would consider the natural ordering and would sort as negative numbers followed by zero followed by positive numbers. This is what Arrays.sort()
does.
If you wish to sort the distances from a reference point , I feel your expected result is not correct. If we consider a line, a reference point and then on its left the negative distance and on its riggt the positive distance then sorting should be based on absolute value.
Your business requirement is to do a custom sorting. For any sorting to work you need to have a logic for comparision. For this java provides Comparator
. You need to implement your business logic based comparision for sorting. [HINT : while comparing you can just compare the absolute value, Math.abs may help]
Floats end with f
so apending f
with each of your array elements is better.
For reference you can see another related question
How to sort an array of ints using a custom comparator?