Open In App

How Can I Efficiently Sort a Large Array in C++?

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, sorting an array means rearranging the elements of an array in a logical order. In this article, we will learn how to efficiently sort a large array in C++.

Example:

Input: myArray = {5, 2, 3, 1, 4......};
Output: Sorted array is : 1 2 3 4 5 ....

Sorting a Very Large Array in C++

To efficiently sort a large array in C++, we can use the std::sort() function from the <algorithm> library that uses a sorting algorithm that is efficient for a wide range of data and sorts the elements in the range [first, last) into ascending order (by default).

Syntax of std::sort()

sort(startIterator, endIterator);

Here,

  • startIterator is an iterator pointing to the start of the range to sort.
  • endIterator is an iterator pointing one past the end of the range to sort.

C++ Program to Efficiently Sort a Large Array

The below example demonstrates the use of std::sort to efficiently sort a large array in C++.

C++
// C++ program to illustrate how to efficiently sort a large
// array
#include <algorithm>
#include <array>
#include <ctime>
#include <iostream>
#include <random>

// defining size
#define BIG_SIZE 10000000

using namespace std;

int main()
{
    // creating a array of the desired size
    int* arr = new int[BIG_SIZE];

    // defining random engine with current time as seed.
    mt19937 mt(time(0));

    // Fill the vector with random values
    for (int i = 0; i < BIG_SIZE; i++) {
        arr[i] = mt();
    }

    // using std::sort to sort the array
    sort(arr, arr + BIG_SIZE);

    // printing the sorted array
    cout << "Sorted Array: ";
    for (int i = 0; i < BIG_SIZE; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}


Output

Sorted Array: -2147483425 -2147483243 -2147483127 -2147482316 -2147481430.....{truncated}

Time Complexity: O(N log N), here N is the number of elements in the array.
Auxiliary Space: O(logN)

Note: The efficiency of sorting a large array is dependent on several factors like size of the array, the distribution of the data, and the specific characteristics of the sorting algorithm used. So, we have to choose a sorting algorithm that best suits our specific use case for optimal performance.




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads