1

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?

4

2 回答 2

3

您正在比较索引而不是值。

改变这个

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

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);
}
于 2018-12-09T22:46:02.980 回答
1

首先,你用String Array nameArray做什么?在您的代码中没有注意到它。如果我理解得很好,我认为你想要这样的东西:

    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());
            }
}
于 2018-12-09T23:01:22.873 回答