External sorting is a term for a class of sorting algorithms that can handle massive amounts of data. External sorting is required when the data being sorted do not fit into the main memory of a computing device (usually RAM) and instead they must reside in the slower external memory (usually a hard drive). External sorting typically uses a hybrid sort-merge strategy. In the sorting phase, chunks of data small enough to fit in main memory are read, sorted, and written out to a temporary file. In the merge phase, the sorted sub-files are combined into a single larger file.
One example of external sorting is the external merge sort algorithm, which sorts chunks that each fit in RAM, then merges the sorted chunks together. We first divide the file into runs such that the size of a run is small enough to fit into main memory. Then sort each run in main memory using merge sort sorting algorithm. Finally merge the resulting runs together into successively bigger runs, until the file is sorted.
Below are the steps used in C++ implementation.
Inputs: input_file : Name of input file. input.txt output_file : Name of output file, output.txt run_size : Size of a run (can fit in RAM) num_ways : Number of runs to be merged Output: 1) Read input_file such that at most 'run_size' elements are read at a time. Do following for the every run read in an array. a) Sort the run using MergeSort. b) Store the sorted run in a temporary file, say 'i' for i'th run. 2) Merge the sorted files using the approach discussed here
Following is C++ implementation of above steps.
This code won’t work on online compiler as it requires file creation permissions. When run local machine, it produces sample input file “input.txt” with 10000 random numbers. It sorts the numbers and puts the sorted numbers in a file “output.txt”. It also generates files with names 1, 2, .. to store sorted runs.
This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Internal and External Commands in Linux
- Know Your Sorting Algorithm | Set 1 (Sorting Weapons used by Programming Languages)
- Know Your Sorting Algorithm | Set 2 (Introsort- C++’s Sorting Weapon)
- Find whether it is possible to make array elements same using one external number
- Calling an External Program in Java using Process and Runtime
- Resetting a root password in Linux without external media
- Input/Output from external file in C/C++, Java and Python for Competitive Programming
- Input/Output from external file in C/C++, Java and Python for Competitive Programming | Set 2
- Internal Linkage and External Linkage in C
- Sorting Big Integers
- Sorting Terminology
- sorting in fork()
- Alternative Sorting
- Sorting Arrays in PHP 5
- Pancake sorting