C++ Online Compiler
Example: Merge Sort Implementation in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Merge Sort Implementation #include <iostream> // For input/output operations #include <vector> // For using std::vector // Function to merge two sorted subarrays // arr[l..m] and arr[m+1..r] into arr[l..r] void merge(std::vector<int>& arr, int left, int mid, int right) { int n1 = mid - left + 1; // Size of the left subarray int n2 = right - mid; // Size of the right subarray // Create temporary arrays std::vector<int> L(n1); std::vector<int> R(n2); // Copy data to temp arrays L[] and R[] for (int i = 0; i < n1; i++) L[i] = arr[left + i]; for (int j = 0; j < n2; j++) R[j] = arr[mid + 1 + j]; // Merge the temp arrays back into arr[left..right] int i = 0; // Initial index of first subarray int j = 0; // Initial index of second subarray int k = left; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } // Copy the remaining elements of L[], if any while (i < n1) { arr[k] = L[i]; i++; k++; } // Copy the remaining elements of R[], if any while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that implements Merge Sort // arr is the array to be sorted, left is the starting index, right is the ending index void mergeSort(std::vector<int>& arr, int left, int right) { if (left >= right) { // Base case: if the array has 0 or 1 element, it's already sorted return; } int mid = left + (right - left) / 2; // Find the middle point to divide the array into two halves mergeSort(arr, left, mid); // Recursively sort the first half mergeSort(arr, mid + 1, right); // Recursively sort the second half merge(arr, left, mid, right); // Merge the sorted halves } // Utility function to print an array void printArray(const std::vector<int>& arr) { for (int x : arr) { std::cout << x << " "; } std::cout << std::endl; } int main() { // Step 1: Initialize an array std::vector<int> arr = {12, 11, 13, 5, 6, 7}; int arr_size = arr.size(); // Step 2: Print the original array std::cout << "Given array is \n"; printArray(arr); // Step 3: Call mergeSort to sort the array mergeSort(arr, 0, arr_size - 1); // Step 4: Print the sorted array std::cout << "\nSorted array is \n"; printArray(arr); // Test with another array std::vector<int> arr2 = {38, 27, 43, 3, 9, 82, 10}; arr_size = arr2.size(); std::cout << "\nGiven array 2 is \n"; printArray(arr2); mergeSort(arr2, 0, arr_size - 1); std::cout << "\nSorted array 2 is \n"; printArray(arr2); return 0; }
Output
Clear
ADVERTISEMENTS