×

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

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

C++ Pointer

Pointer is a derived data type that stores the address of a variable. A pointer is used for memory management and dynamic memory allocation. Pointer works on the address of data rather than...

2 minutes read.

Swap numbers in C++

Swap numbers Swapping refers to interchanging values between two variables. Swapping is important and easy to understand programming logic in the world of coding. Though it is used in the programming...

4 minutes read.

Classes and Objects in C++

When it comes to object-oriented programming, objects are the basic building blocks. Memory is taken up by objects, which contain data and methods or functions that operate on it. On...

3 minutes read.

Factory Method for Designing Pattern in C++

In C++, the factory method is a type of conditional design pattern. The factory method is related to creating a new object in C++. With the help of a factory...

3 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

Roadmap to C++ Programming

Introduction There are so many programming languages available in the market, but among them, C++ is something that never lost its charm. It has a powerful impact on the programming world....

4 minutes read.

Pthreads or POSIX Threads in C++

The thread API for C/C++ is implemented by pthreads or POSIX threads. It enables the multithreading system, which enables parallel and distributed processing, and the creation of new concurrent process...

3 minutes read.

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we...

4 minutes read.

Desired Capabilities in Selenium Web Driver in C++

A class called Desired Capabilities is used to specify a set of fundamental requirements, such as browser, operating system, and version combinations.to carry out automated testing of a web application...

7 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

How to call a void function in C++

Generally, any function has two types: 1. Void function: It doesn't return any value. 2. Non-void function: It returns some value. Program to call a void function in C++ #include <iostream> using namespace std;  void check() {  ...

2 minutes read.

Timsort Implementation Using C++

Timsort Implementation Using C++ The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion...

3 minutes read.

Lexicographically Next Permutation in C++

In this tutorial, we'll look at how to use C++ to generate the lexicographically next permutation of a string. The lexicographically next permutation is the larger permutation. "ACB," for example,...

3 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

C++ Constructor

Constructor is a specific method in C ++ that is automatically called when an object is created. Typically, it is used to set the data members of a new object....

4 minutes read.

Armstrong Number using While Loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

4 minutes read.

OOPs Concepts in C++

C++ Object-Oriented Programming Concepts C++ uses the concept of object-oriented programming. Object Oriented Programming has some prominent features: Object Class Data abstraction Encapsulation Polymorphism Inheritance Message passing Object An object is the basic unit...

2 minutes read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.

Memset in C++

Memset () is a function in the C++ programming language that fills memory blocks. The value of "ch" is first converted to an unsigned character. In this case, "ch" denotes the...

3 minutes read.