Bubblesort根据计数将重复项排序到不同的列表中

时间:2015-12-02 01:07:54

标签: java list count distinct bubble-sort

我有一个上学项目,但我需要一些提示。

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

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

我需要使用Bubblesort来获得一个看起来像这样的独特列表(按每个文档在原始列表中出现的次数排序):

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

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

我已经创建了其他实现,根据每个文档的某些属性创建了一个不同的列表 - 但是现在当面对每个文档在列表中出现的次数时,我不知道是一个干净的解决方案。

编辑:这是我用于作业其他部分的实现(“属性”类似于上面问题中的“文档”)

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

1 个答案:

答案 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);    
       }  
相关问题