Java - 排序ArrayList - 冒泡排序

时间:2014-05-08 04:53:23

标签: java sorting arraylist bubble-sort

我必须对包含购买客户频率的arrayList进行排序。所以我可以按升序或降序显示输出。但是,我不太确定我错过了什么,但它根本没有对元素进行排序。我真的很感激任何意见或反馈!

这是我到目前为止所做的:

for(int i=0; i<customers.size(); i++)
{
        for(int k= i+1; k <customers.size(); k++)
        {
                if((customers.get(k)).compareTo(customers.get(i)) < 0)
                {
                        Customer temp = customers.get(i);
                        customers.set(i, customers.get(k));
                        customers.set(k,temp);

                }
        }

        System.out.println(customers.get(i));   
}

4 个答案:

答案 0 :(得分:0)

保持 K = i ,试试这个内循环:

for(int k= i; k <customers.size() - i -1; k++)
{

这应该有效。

答案 1 :(得分:0)

如果要打印排序列表System.out.println(customers.get(i));必须在排序循环之外。在那个之后添加另一个循环来打印结果

答案 2 :(得分:0)

你有一些错误,

// I tested with List<String>, String temp.
public static void sort(List<Customer> customers) {
  for (int i = 0; i < customers.size() - 1; i++) {
    for (int k = i + 1; k < customers.size(); k++) {
      // Compare left to right, not right to left.
      if (customers.get(i).compareToIgnoreCase(customers.get(k)) > 0) {
        Customer temp = customers.get(i);
        customers.set(i, customers.get(k));
        customers.set(k, temp);
      }
    }
  }
}

当我用

进行测试时
public static void main(String[] args) {
  String[] names = { "Bob", "bob", "Alice", "Bob",
      "Carol" };
  List<String> al = new ArrayList<String>(
      Arrays.asList(names));
  sort(al);
  for (String str : al) {
    System.out.println(str);
  }
}

我得到了

Alice
bob
Bob
Bob
Carol

答案 3 :(得分:0)

尝试一下

int n = yourArray.size();
    for (int i = 0; i < n - 1; i++)
        for (int j = 0; j < n - i - 1; j++)
            if (yourArray.get(j) < yourArray.get(j + 1)) {
                int temp = yourArray.get(j);
                yourArray.set(j, yourArray.get(j + 1));
                yourArray.set(j + 1, temp);`
            }