External Merge Sort Visualizer
Data Management 2022/2023 - Project Report
You can access the visualizer at the following link:
https://valeriodiste.github.io/ExternalMergeSortVisualizer
1. Introduction
1.1. Internal and External Sorting
External sorting algorithms allow for sorting large amounts of data by only considering a small fraction of that data at a time.
They are used when the data being sorted do not fit into the main memory of a computing device (e.g. RAM), and instead must reside in the external memory (e.g. disk drive): this is known as “external memory model”.
In the "internal sorting" approach, used instead when considering arrays or small data structures in general, the entire data to be sorted is loaded in the main (internal) memory before proceeding.
When larger collections of data need to be sorted, however, this approach is not applicable: this is because algorithms following the "internal sorting" approach (like selection sort, merge sort, quick sort, etc.) can afford to consider and manage the entire data being sorted at each single iteration, and operate based on the order of all the elements to sort in that specific iteration.
Larger collections of data which can’t fit into the available memory of a computing device, and must therefore reside in the "external memory" (secondary storage), make the described approach inapplicable
1.2. Possible Approaches
When sorting records of a large relation contained in a file and stored in a database (in secondary storage), in order to be able to replicate the behavior of the "internal sorting" approach, and thus considering all the elements (records) at each iteration of a sorting algorithm (like in the case of merge sort, which needs to take into account specific elements in the merging phase), a possible approach would be to load each element from external (or secondary) memory, into the main memory, one at a time and each time the algorithm requires to analyze that specific element.
Replicating “internal sorting” algorithms in this way, however, would force the loading in main memory of the entire page of the file in which the single element (e.g. a record of a relation) is located, since a page represents the smallest collection of data that can be loaded from secondary storage (i.e. records can't be retrieved one at a time from the secondary storage).
The described approach is highly impractical, mainly because in the external memory model we are not interested in minimizing the amount of times the data is read (as for merge sort and the other internal sorting approaches), but instead in minimizing the number of page accesses of the sorting algorithm for data stored in the external memory (secondary storage), which act as a bottleneck for the time complexity of the sorting algorithms (since the loading of a page from secondary storage is very slow).
A second possible approach to implement a sorting algorithm in the external memory model would be to work directly on the disk (i.e. on the external memory itself) and sort records without using the main memory, but this is, once again, very slow.
Accessing data from an external (secondary) memory is slow because of the absence of an index or a way to univocally retrieve single elements of the stored data (since external memory devices, other than offering higher “data retention” than primary storage devices, are intended to store large amounts of data, and indexing this large amount of data would generate a lot of overhead and oftentimes not be efficient).
This renders searching for a single element of a large collection of data directly from the secondary storage very slow (unless we use a “Direct-Access Storage Device” or DASD, as a secondary storage device, which allows for quick access of stored data through unique addresses assigned to each block of memory).
A third, final and practical approach consists of considering only a small portion of data at a time, at each step of sorting, namely as much data as can fit into the available main memory of the computing device.
This is known as “External Sorting”, because we can sort data stored in the external memory (secondary storage) without the need of loading the entire data collection in the internal memory (which is what happens with “internal sorting” approaches).
The described approach is the best solution in terms of number of accesses to the secondary storage, and therefore also in terms of time complexity if we consider access to secondary storage as a time bottleneck for sorting.
A possible implementation of external sorting is the so-called “external merge sort”.
The main idea is to divide the data to be sorted into smaller chunks, sort them individually, and then merge them together in the correct order, creating larger and larger sorted chunks at each iteration, and eventually obtaining a single sorted collection of data, in a similar way to the internal merge sort algorithm (but with the previously mentioned differences and constraints).
Another possible implementation of external sorting is the “external distribution sort”, which consists of finding “pivot points”, in a similar way to the internal quick sort algorithm, and then use these “pivots” to recursively divide the data to be sorted into smaller and smaller chunks until we get to a size which can fit into a single memory page.
Once we are done partitioning the data, each single chunk can be loaded into the main memory and therefore efficiently be sorted.
Sorted chunks, taken in the order they were partitioned (and then sorted), make up the sorted collection of data of the initial collection.
1.3. External Merge Sort
The following is an introduction to external merge sorting algorithms (external distribution sorting approaches won’t be discussed).
1.3.1. Two-Way External Merge Sort
The simplest implementation of external merge sort is the “two-way” external sorting algorithm.
We start from a relation R containing a certain amount of records and stored into B
pages of a file in secondary storage (and therefore in B blocks of memory).
Usually, the number of pages B of the file will be way larger than the available number of blocks in main memory, and therefore, if we assume to have, in the main memory buffer, only M free blocks of memory (called “frames”), we will only be able to consider M pages of the file for relation R at a time (with the corresponding records contained in those pages).
In an initial “pass” of all the records of the file (that we will call “pass 0”) we can consider a single page of the file at a time, load it into the main memory, sort its records using an efficient internal sorting algorithm (e.g. quick sort or merge sort), and then write the page back into secondary storage.
The B created pages are called “runs”, i.e. sorted portions of the original file.
Once we are done with this initial pass, we can proceed by “merging “ the sorted runs in a similar way to the “merge phase” of the internal merge sort algorithm, using another “pass” of the records stored in the runs (called “pass 1”): we can load the first pages of M-1 runs created in the previous pass into M-1 free frames of the buffer and merge their records into a single new run of M-1 pages.
We only consider M-1 frames because we need to reserve one of the M frames, called “output frame”, for the generated output of the “merge”, hence we need to keep a free frame of the buffer to store the records in order and to then be able to write its content back to the secondary storage.
Whenever the “output frame” is full, we write it into secondary storage and therefore empty it to free space for the next records of the pages we are merging.
Whenever we reach the final record of a page (of a certain run) currently in one of the buffer frames, we load the next page of the corresponding run into the same frame of the buffer, and continue the merging.
After this first pass, we can proceed in the same way for a second pass, and therefore consider a generic “pass i” after “pass 0” as the merge of runs created in “pass i-1”, until we reach a point in which we only have a single run of sorted pages and records, which corresponds to the sorted records of relation R.
The cost of this kind of algorithm in terms of accessed secondary storage blocks of memory is 2×B×N where N is the total number of passes (since at each pass we read once and write back once each of the B pages of the file storing the relation or of the runs created in the previous pass).
The number of passes N will be N = ⌈logM-1(B)⌉+1 (since at each pass we process M-1 runs and merge them into a single run).
The minimum amount of available frames to execute the two-way external merge sorting algorithm is 3 (for which we obtain a cost of 2×B×⌈logM-1(B)⌉+1 memory accesses), since at each pass we need to load at least 2 pages of each run to be merged and we need a frame to reserve for the output of their merge.
1.3.2. K-Way External Merge Sort
In pass 0 of the previous algorithm, we only consider a single page of the file at a time, sort it and write it back in secondary storage.
This can be optimized by reading M pages of the file at a time instead (with M being the number of available frames in the buffer).
We can then proceed as before, considering M-1 pages of runs at the generic pass i of the algorithm and merging them until we can produce a single sorted run (i.e. the sorted file).
With this generalization, we start pass 1 of the algorithm with ⌈B/M⌉ runs instead of B runs, and therefore will merge runs and arrive at the final pass of the algorithm quicker.
The cost of the K-way external sorting algorithm in terms of memory accesses is again 2×B×N where N is the total number of passes.
The number of passes N, in this case, will be N = ⌈logM-1(⌈B/M⌉)⌉+1 (since at each pass we process M-1 runs and merge them into a single run, starting from ⌈B/M⌉ runs produced at pass 0).
1.3.3. Replacement Selection Strategy
While producing runs for pass 0 of the aforementioned k-way external merge sorting algorithms, we can produce a maximum total number of runs equal to the number of available frames M in the buffer of the main memory.
We optimize pass 0 by trying to create more than M runs to then merge this smaller amount of runs in the generic i-passes of the algorithm even quicker.
The “replacement selection” strategy aims to do this by using a “priority queue” Q1 to assign a certain priority to records currently loaded in the buffer: we reserve a frame for the output and also a frame for the input, and work with M-2 frames which will hold the records of the file which compose queue Q1.
At each iteration of pass 0, we find the minimum record r1 in queue Q1 and “move it” into the output frame, then choose one of the records in the input frame, which we will name r2, to replace the now free slot of record r1 in its corresponding frame (among the M-2 frames we are using).
If this record r2 is greater than record r1, we insert r2 into the priority queue Q1 to be analyzed in one of the next iterations of pass 0.
If, instead, record r2 is smaller than the record we just wrote into the output frame, we insert r2 into a second priority queue, Q2, which we will use later.
Whenever the input frame is empty, we load the next page of the file into the input frame, and continue with the execution of pass 0.
This procedure allows us to create a sorted run containing all the records we will find in queue Q1, which may be more than just the records we can fit into M pages of the buffer (as instead happens in the k-way variation of the algorithm), and therefore may produce a run of more than M pages.
When we can’t find records in queue Q1 (hence Q1 empties out), this means that no more record r1 can be found such that r1 is greater than the last record written in the run we are currently creating (i.e. written in the output frame before copying the output frame in secondary storage to extend the current run).
We will therefore need to turn to a new run, and we can do this by moving what is now the content of queue Q2 into the empty queue Q1.
We can now start the creation of a new run as described before, each time replacing the records we pull out from queue Q1 with records in the input frame, and move Q2 to Q1 each time Q1 is empty.
When no more pages of the file can be loaded into the input frame, we simply continue with the algorithm until queues Q1 and Q2 are empty, and then start pass 1 with the generated runs, which may likely have a dishomogeneous number of pages and records, and merge these runs in the subsequent passes as described for the two-way and k-way versions of the algorithm.
The number of runs created at pass 0 is, on average, half of the runs we can produce with pass 0 of the k-way sorting algorithm, meaning that we will be able to eventually merge these runs into a single sorted collection in about half the number of passes we need for the k-way algorithm.
Note that this is an “average case” complexity in terms of memory accesses, since we cannot accurately predict how many runs will be produced starting only from the number of pages of the file B and the number of available frames in the buffer M (as instead we can do with the two-way and k-way approaches).
In a worst case analysis, instead, the number of runs produced at pass 0 may be as large as B (the same number of runs produced at pass 0 using the two-way version of the algorithm).
1.3.4. Other Optimizations
Various kinds of optimizations and variations of the external merge sort algorithm exist.
One of the main optimizations we can consider is the “double buffering” approach, which makes up for the problem of needing to wait for input/output operations executed on the slower secondary storage before being able to proceed with operations of the faster main memory buffer.
The “double buffering” approach partitions the free frames of the buffer into two separate portions, which can individually be considered as a buffer: while input and output operations need to be performed to load or write pages from and into secondary storage for one of the 2 buffers, the main memory can still operate on the other buffer and manipulate and analyze records that were previously loaded in it.
2. Algorithms Visualization

The original project idea consisted of designing and implementing a software for visualizing the external sorting algorithm, with varying size of the relation and varying number of frames in the buffer.
For the final developed project work, the two-way, k-way, and replacement selection variations of the external sorting algorithm were considered for the visualization, and additional features and customization options were implemented and added.
A common algorithm aggregating the 3 possible considered variations of the external merge sort algorithm was considered, with the following pseudocode: