Nicola
Nicola

Reputation: 331

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?

Upvotes: 1

Views: 119

Answers (2)

eyelash
eyelash

Reputation: 112

First of all, for what do you use the String Array nameArray? Didn't noticed it in your code. If I understood it well I think you want something like this:

    public void bubble_sort(ArrayList<String> nameArray, ArrayList<BigDecimal> priceArray){

        boolean swap=true;
        double temp=0;
        while (swap){
        swap=false;
        for (int i = 0; i < priceArray.size()-1; i++){
       if (priceArray.indexOf(j) > priceArray.indexOf(j+1)){
            temp = priceArray.indexOf(j);
            priceArray.set(j, priceArray.get(j+1));
            priceArray.set(j+1, BigDecimal.valueOf(temp));
        }
        swap=true
        }
        }
}
                Log.v("Ordering array", priceArray.toString());
            }
}

Upvotes: 1

DutChen18
DutChen18

Reputation: 1173

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);
}

Upvotes: 3

Related Questions