来自.txt文件的Mergesort行

时间:2016-12-16 19:14:57

标签: java algorithm sorting

我有一个包含多个排序行的文件。 现在我想将所有这些行排序到新文件中的一个合并行。不加载所有数字。

这是我文件的一部分:

12,86,280,304,350,359,371,391,405,548,
255,264,325,346,435,466,483,
39,114,214,298,317,377,428,438,575,
35,165,183,281,336,367,386,418,438,593,
44,77,97,117,122,156,251,415,533,
109,155,163,172,212,226,340,358,452,577,592,
33,74,91,204,256,307,357,388,534,552,554,570,
50,99,246,309,345,358,395,405,419,425,566,

现在我想合并那些,所以首先我需要知道文件有多少行。然后我需要获取所有第一个元素并进行比较。我写入新文件的最低值。然后我要从我刚刚写完的那一行得到第二个数字。并将它们与其他行的第一个数字进行比较。我该怎么做呢。我为Arraylists编写了一个Mergesort:

      //as long as there is unsorted data
        while (listOfOutputs.size() > 0) {
            //Set the lowest undefined
            List<Integer> lowest = null;
            for (List<Integer> list : listOfOutputs) {
                //if the lowest is undefined, I'm the lowest
                if (lowest == null) {
                    lowest = list;
                    //Else am I lower then the lowest? Then I'm the lowest
                } else if (list.get(0) < lowest.get(0)) {
                    lowest = list;
                }
            }

            //Finally the lowest is added to the sorted list and removed to from his own list.
            assert lowest != null;
            sortedList.add(lowest.remove(0));

            //Is the size of the list which contained to lowest now 0, remove him from the listOfOutputs
            if (lowest.size() == 0) listOfOutputs.remove(lowest);
        }

但我不知道如何将其重写为对我的文件进行排序的文件。如何在不将它们加载到列表中的情况下执行此操作。

斯文

1 个答案:

答案 0 :(得分:0)

您可以使用简单的双向合并将两行合并为一行,重复该过程,直到生成单个排序行。

假设k是行数,您可以实现k路合并,可能使用堆来优化查找哪条线具有最小的第一个元素。每个堆元素都包含对行的引用以及与该行的当前元素的索引(或指针)的等效项。堆由每行的当前元素排序,以便堆的头引用具有当前最小元素的行。堆由所有k行的第一个元素初始化。

对于每个合并步骤,将删除堆头(具有最小元素的行)的行,将最小元素附加到输出行,并将具有最小元素的行添加回堆中基于其下一个元素。

当到达行尾时,合并将缩减为k-1路合并,最终只会复制到合并输出的一行。

相关问题