问题
problem : i employed a certain sorting method, but it didn't work out as i expected and i fail to understand where did i possibly err.
My code took input(which are numbers) as Strings into an string array and then converted them into Bigdecimal numbers while i compared them, and then rearranged them accordingly in the array as strings
the code in question:
String s[]={-100, 50, 0, 56.6, 90, 0.12, .12, 02.34, 000.000};
for(int i=0;i<n-1;i++)
{
for (int j =i+1; j<n; j++)
{
BigDecimal d = new BigDecimal(s[j]);
BigDecimal a = new BigDecimal(s[i]);
if(a.compareTo(d)==-1)
{
String m = s[j];
s[j]=s[i];
s[i]=m;
}
}
}
//output :90, 56.6, 50, 02.34, .12, 0.12, 0, 000.000, -100
//expected output :90, 56.6, 50, 02.34, 0.12, .12, 0, 000.000, -100
Constraints : s[n]
should be a string array and if two inputs have same values they should be listed in the array in the same order we entered them.
i don't understand why 0.12 and .12 are not output in the same order as i entered them, if the algorithm is somewhere wrong then even 0 and 000.000 should not have have appeared in the same order as i entered them, but instead they did.
回答1:
Well, since you want to use String numbers, you will have to wrap them in quotations, but your sorting can be much more readable. I would suggest the following
String[] numbers ={"-100", "50", "0", "56.6", "90", "0.12", ".12", "02.34", "000.000"};
List<BigDecimal> decimalList = new ArrayList<>();
for(String s: numbers){
decimalList.add(new BigDecimal(s));
}
Collections.sort(decimalList);
Collections.reverse(decimalList); // edit , forgot this line
decimalList.forEach(System.out::println);
回答2:
You can use a Stream
and pass a custom comparator to sorted
and then collect
and print. Like,
String s[] = { "-100", "50", "0", "56.6", "90", "0.12", ".12", "02.34", "000.000" };
System.out.println(Stream.of(s)
.sorted((a, b) -> new BigDecimal(b).compareTo(new BigDecimal(a)))
.collect(Collectors.joining(", ")));
And I get (as requested)
90, 56.6, 50, 02.34, 0.12, .12, 0, 000.000, -100
来源:https://stackoverflow.com/questions/47114295/why-does-my-sorting-method-for-bigdecimal-numbers-fails-to-sort