0% found this document useful (0 votes)
3 views

Merge Sort Using Recursion

The document provides a C++ implementation of the Merge Sort algorithm using recursion. It includes functions for merging sorted subarrays, performing the merge sort, and printing the array. The main function demonstrates sorting an example array and displaying the results before and after sorting.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Merge Sort Using Recursion

The document provides a C++ implementation of the Merge Sort algorithm using recursion. It includes functions for merging sorted subarrays, performing the merge sort, and printing the array. The main function demonstrates sorting an example array and displaying the results before and after sorting.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Merge Sort Using Recursion:

#include <iostream>
using namespace std;

void merge(int arr[], int left, int mid, int right) {


int n1 = mid - left + 1;
int n2 = right - mid;

int L[n1], R[n2];

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];

int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) arr[k++] = L[i++];
else arr[k++] = R[j++];
}

while (i < n1) arr[k++] = L[i++];


while (j < n2) arr[k++] = R[j++];
}

void mergeSort(int arr[], int left, int right) {


if (left < right) {
int mid = left + (right - left) / 2;

mergeSort(arr, left, mid);


mergeSort(arr, mid + 1, right);

merge(arr, left, mid, right);


}
}

void printArray(int arr[], int size) {


for (int i = 0; i < size; i++) cout << arr[i] << " ";
cout << endl;
}

int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int size = sizeof(arr) / sizeof(arr[0]);

cout << "Given array: ";


printArray(arr, size);

mergeSort(arr, 0, size - 1);

cout << "Sorted array: ";


printArray(arr, size);

return 0;
}

You might also like