【问题标题】:Ordering an ArrayList<BigDecimal> with bubble sort使用冒泡排序对 ArrayList<BigDecimal> 进行排序
【发布时间】:2019-05-10 20:45:48
【问题描述】:

我正在尝试订购一个 Arraylist,其中包含从最大到最小的 BigDecimal 货币价值。 这是我的代码:

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

}

但是顺序还是和原来的数组一样。 我该怎么办?

【问题讨论】:

  • 使用priceArray.get(j).compareTo(priceArray.get(j+1)) &gt; 0 而不是这个:priceArray.indexOf(j) &gt; priceArray.indexOf(j+1)
  • 谢谢,但现在它为每个价格打印“-1”,而不是价值。 --> 如果大小为 3,则打印 [-1, -1, -1]。也许我的代码中的其他地方有问题?

标签: java android arraylist bubble-sort


【解决方案1】:

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

改变这个

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

【讨论】:

  • 谢谢,但现在它为每个价格打印“-1”,而不是价值。 --> 如果大小为 3,则打印 [-1, -1, -1]。也许我的代码中的其他地方有问题?
  • @Nicola 您还为索引设置了新值而不是交换它们,现在应该修复。
  • 是的,谢谢,现在可以了!我还将 > 0 更改为
【解决方案2】:

首先,你用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());
            }
}

【讨论】:

    猜你喜欢
    • 2019-06-14
    • 2014-06-25
    • 2017-09-27
    • 2022-01-25
    • 2011-06-05
    • 2021-12-13
    • 2013-10-31
    • 2020-07-17
    • 2021-12-31
    相关资源
    最近更新 更多