2015-12-02 61 views
1

我有一个学校项目,但我需要一些提示。Bubblesort根据计数重新排列到不同的列表中

我有一个看起来像这样一个ArrayList:

[0] Document 1 
[1] Document 1 
[2] Document 2 
[3] Document 3 
[4] Document 3 
[5] Document 3 
[6] Document 4 

我需要使用冒泡得到一个不同的列表,看起来像这样(由OCCURENCES每个文件在最初的名单有数量排序):

[0] Document 3 
[1] Document 1 
[2] Document 2 
[3] Document 4 

我可以自由地创建一个新的ArrayList或者使用一个外部for循环的完成它 - 但它需要由冒泡排序。

我已经创建了其他实现,基于每个文档的某些属性创建一个不同的列表 - 但是现在,当面对每个文档在列表中出现的次数时,我对丢失一个干净的解决方案感到迷茫。

编辑:这是我用于分配的其他地方的执行(“属性”类似于上面我的问题“文件”)

int r = attributes.size() - 1; 
    boolean swapped = true; 
    while(swapped && r >= 0) { 
     swapped = false; 
     for(int i = 0; i < r; i++) { 
      Attributes current = attributes.get(i); 
      Attributes next = attributes.get(i + 1); 
      if(current.occurrence > next.occurrence) { 
       swapped = true; 
       attributes.set(i, next); 
       attributes.set(i + 1, current); 
      } 
     } 
     r--; 
    } 
+0

但气泡排序的目的是按订单排序。为什么您的输出中的dos无序? –

+0

对不起,它可能不清楚,所以我编辑的重要。新列表按照第一个列表中出现的次数排序。由于3是原始列表中的三次,因此它的计数最高。 –

+0

好吧,所以你必须使用气泡排序(你自己的创作?)按频率排序文档对象在数组列表中的出现次数,从最大到最小?你有什么代码你尝试过吗? –

回答

0

给你一个样板例如,你可以使用像这样的东西。

List<Integer> arrList = Arrays.asList(5, 0, 0, 2); 
    int freq = Collections.frequency(arrList, "0); 

     System.out.println("Frequency of '0' is: "+freq);  
     } 
+0

由于OP不允许使用标准排序,我非常怀疑他被允许使用'Collections.frequency'。 – dasblinkenlight

+0

@dasblinkenlight哈哈是的,我想这是真的。 –

+0

这解决了它干净,在我的内循环中,我能够使用此语句: if(Collections.frequency(documents,current.document)