Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

java - Why does my sorting method for Bigdecimal numbers fails to sort?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...