If data to be sorted doesn’t fit into main memory external sorting is applicable. External merge sort can be separated into two phases:
- Create initial runs (run is a sequence of records that are in correct relative order or in other words sorted chunk of original file).
- Merge created runs into single sorted file.
Let’s assume that M records at the same time are allowed to be loaded into main memory. One of the ways to create initial runs is to successively read M records from original file, sort them in memory and write back to disk.
The core structure behind this algorithm is priority queue. Taking one by one current minimum element out of the queue forms ordered sequence.
The algorithm can be described as follows:
- Create two priority queues (that will contain items for current and next runs respectively) with capacity of M records.
- Prefill current run priority queue from unsorted file with M records.
- Create current run if there are elements in the current run priority queue:
- Take minimum element out of current run priority queue and append it to current run (basically write it to disk).
- Take next element from unsorted file (this is the replacement part of the algorithm) and compare it with just appended element.
- If it is less then it cannot be part of the current run (or otherwise order will be destroyed) and thus it is queued to the next run priority queue.
- Otherwise it is part of the current run and it is queued to the current run priority queue.
- Continue steps 1 through 4 until current run priority queue is empty.
- Switch current and next runs priority queues and repeat step 3.
At any given moment at most M records are loaded into main memory as single written element into current run is replaced with single element from unsorted file if any (depending on comparison it either goes into current or next run).
Next step is to merge created initial runs. For the merge step we will use simplified algorithm based on k-way merge.
- Append created runs into a queue.
- Until there are more than one run in the queue:
- Dequeue and merge K runs into a single run and put it into the queue.
- Remaining run represents sorted original file.
No comments:
Post a Comment