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
- -100
- 50
- 0
- 56.6
- 90
- 0.12
- .12
- 02.34
- 000.000
Advertisement
Answer
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]