Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting BigDecimal

What is the problem with this BigDecimalSorting? The code takes in numbers as string and then converts it to BigDecimal and then sort and print the sorted BigDecimals.

import java.math.BigDecimal;
import java.util.*;

class Solution {
public static void main(String []argh){

    Scanner sc= new Scanner(System.in);
    int n=sc.nextInt();
    String []s=new String[n];
    BigDecimal a[] = null;

    for(int i = 0; i < n ; i++){
        s[i]=sc.next();
        a[i] = new BigDecimal(s[i]);
    }
    for(int i = 0; i < n-1; i++){
        for(int j = 1; j < n; j++){
            if(a[i].compareTo(a[j]) == -1){
                BigDecimal temp = a[j];
                a[j] = a[i];
                a[i] = temp;
            }
        }
    }
    //Output
    for(int i=0;i<n;i++){
        s[i] = a[i].toString();
        System.out.println(s[i]);
    }
}
}

Sample Input: 9 -100 50 0 56.6 90 0.12 .12 02.34 000.000

Expected Output: 90 56.6 50 02.34 0.12 .12 0 000.000 -100

like image 481
Pratyaksh Prajapati Avatar asked Dec 30 '25 06:12

Pratyaksh Prajapati


2 Answers

You can use the comparator to sort the BigDecimal

import java.math.BigDecimal;
import java.util.*;

class Solution{

public static void main(String []args){
    Scanner sc= new Scanner(System.in);
    int n=sc.nextInt();
    String []s=new String[n+2];
    for(int i=0;i<n;i++){
        s[i]=sc.next();
    }
    sc.close();

    Arrays.sort(s, 0, n, new Comparator<Object>() {
        public int compare(Object a1, Object a2) {
            BigDecimal bigDec1 = new BigDecimal((String) a1);
            BigDecimal bigDec2 = new BigDecimal((String) a2);
            return bigDec2.compareTo(bigDec1);
        }
    });


    //Output
    for(int i=0;i<n;i++)
    {
        System.out.println(s[i]);
    }
}
like image 173
Sahil Avatar answered Jan 01 '26 19:01

Sahil


import java.math.BigDecimal;
import java.util.*;
class Solution{

    public static void main(String []argh)
    {
        Scanner sc= new Scanner(System.in);
        int n=sc.nextInt();
        String []s=new String[n+2];
        for(int i=0;i<n;i++)
        {
            s[i]=sc.next();
        }

        for(int i=0;i<n;i++)
        {
            BigDecimal max=new BigDecimal(s[i]);
            int idx=i;
            for(int j=i+1;j<n;j++)
            {
                BigDecimal curr=new BigDecimal(s[j]);
                if(curr.compareTo(max)==1)
                {
                    max=curr;
                    idx=j;
                }
            }
            String temp=s[i];
            s[i]=s[idx];
            s[idx]=temp;
        }

        for(int i=0;i<n;i++)
        {
            System.out.println(s[i]);
        }

    }


}
like image 35
Shubham Pandey Avatar answered Jan 01 '26 19:01

Shubham Pandey