简体   繁体   English

Java Bubble-Sort 不检查最后一个循环通过

[英]Java Bubble-Sort Not checking the last loop through

I am trying to sort an ArrayList but hit a wall at the moment.我正在尝试对 ArrayList 进行排序,但目前碰壁了。 Below, I have a getId() function that retrieves the id of a member.下面,我有一个 getId() function 检索成员的 id。 I want to sort the ArrayList by member id.我想按成员 ID 对 ArrayList 进行排序。 I have checked a afew good articles on this and implemented the following:我已经检查了一些关于此的好文章并实施了以下内容:

eg (before sort) 11 22 33 44 55 66 77 88 99 00例如(排序前)11 22 33 44 55 66 77 88 99 00

eg (after sort) 00 11 22 33 44 55 66 77 88 99例如(排序后)00 11 22 33 44 55 66 77 88 99

Member temp;

for (int i = 0; i < members.size(); i++) {
    Member s = members.get(i);
    System.out.println("S: "+s.getId());
            
    for (int j=0; j < members.size()-1; j++) {
        Member t = members.get(j+1);
        System.out.println("T: "+t.getId());
                
        if (s.getId() > t.getId()) {
        temp = s;
        s = t;
        t = temp;
        }
     }
  }
}

I did the printout statements above to trace the root cause but still trying to figure out the error.我做了上面的打印输出语句来追踪根本原因,但仍然试图找出错误。

The code for swapping is wrong:交换代码错误:

if (s.getId() > t.getId()) {
   temp = s;
   s = t;
   t = temp;
}

Here you only swap s with t , but the data underlying members are not affected.在这里,您仅将st交换,但基础members的数据不受影响。 The correct one:正确的:

for (int i = 0; i < members.size() - 1; i++) {
     for (int j = 0; j < members.size() - i - 1; j++) {
         Member s = members.get(j);
         Member t = members.get(j+1);
         if (s.getId() > t.getId()) {
             Collections.swap(members, j, j+1);
         }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM