×

External merge sort in C++

External merge sort in C++

External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted does not fit into a computer device's primary memory and, instead, it must reside in the lighter external memory. Typically, external sorting developed a hybrid merging tactic. Amounts of information small enough to fit into primary memory are read, sorted, and written to a temporary file during the sorting process. The sorted sub-files are merged into a single bigger file during the merge phase.

Algorithm:

  • Read the input file, and that at many other components of 'run size' is the view at a time.
  • Next, read inside an array per each run.
  • Order the execution using Merge Sort.
  • Store the array sorted into a file. Let's say 'i' for file i.
  • Use the approach discussed to merge k sorted arrays to fuse the sorted files

Example:

#include <iostream>
#include <algorithm>
#include <queue>
#include <limits>
using namespace std;
struct MinHeapNode
{
          int element;
          int k;
};
struct comp
{
          bool operator()(const MinHeapNode lhs, const MinHeapNode rhs) const
          {
                   return lhs.element > rhs.element;
          }
};
FILE* openFile(char* fileName, char* mode)
{
          FILE* fp = fopen(fileName, mode);
          if (fp == NULL)
          {
                   perror("Error detected while opening the file.\n");
                   exit(EXIT_FAILURE);
          }
          return fp;
}
void mergeFiles(char *output_file, int n, int k)
{
          FILE* in[k];
          for (int j = 0; j < k; j++)
          {
                   char fileName[2];
                    // convert i to string
                   snprintf(fileName, sizeof(fileName), "%d", j);
                   in[i] = openFile(fileName, "r");
          }
          FILE *out = openFile(output_file, "w");
          MinHeapNode harr[k];
          priority_queue<MinHeapNode, vector<MinHeapNode>, comp> pq;
          int i;
          for (i = 0; i < k; i++)
          {
                   if (fscanf(in[i], "%d ", &harr[i].element) != 1)
                             break;
                   harr[i].i = i;
                   pq.push(harr[i]);
          }
          int count = 0;
          while (count != i)
          {
                   MinHeapNode root = pq.top();
                   pq.pop();
                   fprintf(out, "%d ", root.element);
          .
                   if (fscanf(in[root.i], "%d ", &root.element) != 1 )
                   {
                             root.element = numeric_limits<int>::max();
                             count++;
                   }
                   // Replace root with next element of input file
                   pq.push(root);
          }
          // close input and output files
          for (int i = 0; i < k; i++)
                   fclose(in[i]);
          fclose(out);
}
void createInitialRuns(char *input_file, int run_size, int num_ways)
{
          // For big input file
          FILE *in = openFile(input_file, "r");
          // output scratch files
          FILE* out[num_ways];
          char fileName[2];
          for (int i = 0; i < num_ways; i++)
          {
                   // convert i to string
                   snprintf(fileName, sizeof(fileName), "%d", i);
                   // Open output files in write mode.
                   out[i] = openFile(fileName, "w");
          }
          int* arr = new int[run_size];
          bool more_input = true;
          int next_output_file = 0;
          int i;
          while (more_input)
          {
                   for (i = 0; i < run_size; i++)
                   {
                             if (fscanf(in, "%d ", &arr[i]) != 1)
                             {
                                      more_input = false;
                                      break;
                             }
                   }
                   sort(arr, arr + i);
                   for (int j = 0; j < i; j++)
                             fprintf(out[next_output_file], "%d ", arr[j]);
                   next_output_file++;
          }
          // deallocate memory
          delete arr;
          // close input and output files
          for (int i = 0; i < num_ways; i++)
                   fclose(out[i]);
          fclose(in);
}
// Program to demonstrate external sorting
int main()
{
          // No. of partitions of input file
          int num_ways = 10;
          // The size of each partition
          int run_size = 1000;
          char input_file[] = "input.txt";
          char output_file[] = "output.txt";
          FILE* in = openFile(input_file, "w");
          srand(time(NULL));
          // generate input
          for (int i = 0; i < num_ways * run_size; i++)
                   fprintf(in, "%d ", rand());
          fclose(in);
          createInitialRuns(input_file, run_size, num_ways);
          mergeFiles(output_file, run_size, num_ways);
          return 0;
}

Complexity Analysis:

Time Complexity: O(n + run_size log run_size).

The time needed by the merge sort is O(nlogn). However, there are components in the most run size. Thus the time complexity is O(run size log run size), but then the time complexity is O(n) to merge the sorted arrays. The multiply-accumulate of the time also is O(n + run size log run size).

Auxiliary space:O(run_size).

The run size was its space required for array storage.

One such code will not work on compiler online, as it needs permissions to create files. So, if running a local machine, the sample input file "input.txt" is produced with different characters of 10000. It sorts the number and put the numbers sorted in an "output.txt" file. It also produces files with names 1, 2, .. Sorted passes to shop.


Related Topics

Decimal to Binary in C++

What is the meaning of Decimal Numbers? Decimal numbers range from 0 to 9, there are a total of ten digits between 0 and 9. Any number with more than two...

3 minutes read.

Passing by Reference Vs. Passing by the pointer in C++

 Passing by Reference Vs. Passing by the pointer in C++ Throughout C++, it can transfer parameter values except by pointers or through referring to a function. For both cases, we have...

3 minutes read.

Sizeof() Operators in C++

sizeof() Operators in C++ The sizeof() operator in C++ defines the size of variables, constants, or data types. It is a unique operator that manipulates other operators and returns the size...

4 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

Handling multiple clients on the Server with multithreading using Socket Programming in C or C++

To understand this guide completely, the reader is assumed to be familiar with the foundations of server and client models and socket programming. If one wants to create any scalable...

7 minutes read.

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages. C++ Function A function is a set of statements that executes a task....

5 minutes read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.

Print Table Using For-loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

3 minutes read.

Function Pointer in C++

Definition: A function pointer in C++ is the same as a usual pointer which is used to point some variables. Function pointers are used to point functions or say store the...

4 minutes read.

C++ Program For FCFS (First Come First Serve)

The most basic scheduling technique is FCFS, often known as "FIFO (First In, First Out)". In this procedure, the first one is utilized and executed first, while the second one...

4 minutes read.

C++ Virtual Destructor

In C++, a destructor is a class member function that is used to free up space or remove an object of the class that has gone out of scope. The...

4 minutes read.

Hello World Program in C++

The steps for “Hello World” C++ program are as follows: Write a C++ code given below in an editor. Save the file with .cpp Compile the code using C++ compiler or using online...

3 minutes read.

Program to find the GCD of two numbers in C++

Before understanding the program of GCD or HCF, one must know what GCD or HCF is. What is GCD? The GCD is referred to as Greatest Common Divisor. HCF is the other...

8 minutes read.

Type conversion in C++

Type conversion is the process of changing the type of variables in a program. The ultimate goal of type conversions is to allow variables of a single data type operate with...

7 minutes read.

Processing strings using std string stream in C++

A string class object called std: string stream is used to streamline into various variables, just as files can pour into strings. This class's things make use of a string...

3 minutes read.

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 minutes read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

Principles of Object-Oriented Programming in C++

What is Object-Oriented Programming? Object-oriented programming is about creating obejcts that represent the real-world entity . In object-oriented programming, objects are created for the class. One of the main objectives of...

5 minutes read.