Home > database >  Big Decimal array not sorting 0 and 000.000
Big Decimal array not sorting 0 and 000.000

Time:11-20

I was solving a java HackerRank problem in which I had to sort an array consisting decimal numbers using BigDecimal class in descending order. The solution works fine except for one case in which 0 and 000.000 comes. Now as they are equal, the problem tells us not keep them in the same order of their occurrence, but it is not happening.

My Code:

    import java.io.*;
    import java.math.*;
    import java.util.*;
    
    public class Solution {
    
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            int n = input.nextInt();
            String [] array = new String[n];
            for(int i=0; i<array.length; i  ){
                array[i] = input.next();
            }
            String temp;
            for(int i= array.length-1; i>=0; i--){
                for(int j=i-1; j>=0; j--){
                    if(new BigDecimal(array[i]).compareTo(new BigDecimal(array[j]))>0){
                        temp = array[i];
                        array[i] = array[j];
                        array[j] = temp;
                    }
                }
            }
            for(int i=0; i<array.length; i  ){
                System.out.println(array[i]);
            }          
        }
    }

Sample Input : 9 ---> the size of array

  1. -100
  2. 50
  3. 0
  4. 56.6
  5. 90
  6. 0.12
  7. .12
  8. 02.34
  9. 000.000

CodePudding user response:

I changed quite a few things in your code. Take a look at it.

Scanner input = new Scanner(System.in);
int n = input.nextInt(); // getting the size

List<BigDecimal> numbers = new ArrayList<>(); // Creating a list that holds our BigDecimals
for (int i = 0; i < n; i  )
{
    double tmp = input.nextDouble(); // Getting the value as a Double and not as a string. It makes no sense to parse the string into a number later again
    numbers.add(BigDecimal.valueOf(tmp)); // Adding the double value as a BigDecimal
}

numbers.sort(BigDecimal::compareTo); // Sorting the list through the help of .compareTo() function

for (BigDecimal s : numbers)
{
    System.out.println(s);
}

Try to avoid strings when you take input from the user, you should force number input and not get some gibberish and then try to parse it, it will lead to problems later, it is better to handle wrong input at the moment it comes in.

CodePudding user response:

You problem is stability of sort. You should select a stable sort algorithm. Insertion sort is such one.

String temp;
for (int i = 0; i < n; i  ) {
    for (int j = i; j > 0
        && new BigDecimal(array[j - 1]).compareTo(new BigDecimal(array[j])) < 0; j--) {
        temp = array[j - 1];
        array[j - 1] = array[j];
        array[j] = temp;
    }
}
System.out.println(Arrays.toString(array));

output:

[90, 56.6, 50, 02.34, 0.12, .12, 0, 000.000, -100]
  • Related