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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…