-1

I have an array of distances calculated using (distance to) method which contain both negative and positive values looks like this

float num[] = {-123.81944, 34.56723, -133.40782};    

when trying to use

Arrays.sort(num);  

the result is

-123.81944     
-133.40782    
34.56723

which is incorrect since -133.40782 location is closer than -123.81944

how can i sort the array to result like this

-133.40782      
-123.81944     
  34.56723 
Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
Abdul2511
  • 153
  • 1
  • 4
  • 14
  • 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. – nits.kk Jul 03 '17 at 04:34
  • so your code as posted does not compile. when simple changes are made so that it compiles the result is as you want - so what exactly is your question? – Scary Wombat Jul 03 '17 at 04:53

3 Answers3

1

If you want to use float as data type, then you should declare the array as follows. Otherwise, you can use double as data type to avoid adding a suffix f to the numbers.

float[] num = {-123.81944f, 34.56723f, -133.40782f};
// or, double[] num = {-123.81944, 34.56723, -133.40782};
Arrays.sort(num);
System.out.println(Arrays.toString(num));

Output

[-133.40782, -123.81944, 34.56723]

See a live demo.

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
1

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?

nits.kk
  • 5,204
  • 4
  • 33
  • 55
-1

For me, with a standard Java JRE it works like (you) expected, but I had to turn the numbers in float literals. Otherwise it did not compile:

float num[] = new float[] {-123.81944f, 34.56723f, -133.40782f};
Arrays.sort(num);
for (int i = 0; i < num.length; i++) {
  System.out.print(" " + num[i]);
}

prints -133.40782 -123.81944 34.56723

Florian S.
  • 386
  • 1
  • 12