Search code examples
javaandroidarraylistbubble-sort

Ordering an ArrayList<BigDecimal> with bubble sort


I'm trying to order an Arraylist which contains BigDecimal value of money from the largest to the smallest. That's my code:

 public void bubble_sort(ArrayList<String> nameArray, ArrayList<BigDecimal> priceArray){
    for (int i = 0; i < priceArray.size(); i++){
        for (int j = 0; j < priceArray.size() - 1; j++){
            if (priceArray.indexOf(j) > priceArray.indexOf(j+1)){
                int temp = priceArray.indexOf(j);
                priceArray.set(j, priceArray.get(j+1));
                priceArray.set(j+1, BigDecimal.valueOf(temp));
            }
        }
    }
    Log.v("Ordering array", priceArray.toString());

}

But the order is still the same of the original array. What should I do?


Solution

  • You are comparing the indices instead of the values.

    Change this

    if (priceArray.indexOf(j) > priceArray.indexOf(j+1)){
        int temp = priceArray.indexOf(j);
        priceArray.set(j, priceArray.get(j+1));
        priceArray.set(j+1, BigDecimal.valueOf(temp));
    }
    

    to

    if (priceArray.get(j).compareTo(priceArray.get(j+1) > 0){
        BigDecimal temp = priceArray.get(j);
        priceArray.set(j, priceArray.get(j+1));
        priceArray.set(j+1, temp);
    }