簡體   English   中英

.txt文件中的Mergesort行

[英]Mergesort lines from a .txt file

我有一個包含多行排序的文件。 現在,我想將所有這些行歸為一個新文件中的合並行。 無需一次加載所有數字。

這是我文件的一部分:

 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, 

現在,我想對它們進行排序,所以首先我需要知道文件有多少行。 然后,我需要獲取所有最初的元素並進行比較。 我寫到新文件的最低價。 然后,我必須從剛寫過的那一行中獲取第二個數字。 並將它們與其他行的第一個數字進行比較。 我該怎么做呢。 我為數組列表編寫了一個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); } 

但是我不知道如何將其重寫為對我的文件進行排序的文件。 我如何做到這一點,而不將它們加載到列表中。

斯文

您可以使用簡單的2種方式合並,一次將2條線合並為一條線,重復此過程,直到產生一條排序的線。

要么

假設k是行數,則可以實現ak方式合並,可能使用堆來優化查找哪一行具有最小的第一元素。 每個堆元素都包含對line的引用,以及對該行當前元素的索引(或指針)等效項。 堆按每行的當前元素排序,以便堆的頭引用具有當前最小元素的行。 堆由所有k行的第一個元素初始化。

對於每個合並步驟,將從堆頭開始的行(具有最小元素的行)被刪除,將最小元素附加到輸出行,並將具有最小元素的行根據其合並回添加到堆中。下一個元素。

當到達一行的末尾時,合並將減少為k-1方式的合並,最終僅將一行復制到合並的輸出中而結束。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM