0% found this document useful (0 votes)
3 views2 pages

Merge Sort Code

The document contains a C++ implementation of the merge sort algorithm. It defines two main functions: 'merge' to combine sorted subarrays and 'mergeSort' to recursively sort the array. The 'main' function demonstrates sorting an example array and printing the sorted result.

Uploaded by

zarnabm476
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Merge Sort Code

The document contains a C++ implementation of the merge sort algorithm. It defines two main functions: 'merge' to combine sorted subarrays and 'mergeSort' to recursively sort the array. The 'main' function demonstrates sorting an example array and printing the sorted result.

Uploaded by

zarnabm476
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Merge sort Code:

#include <iostream>

using namespace std;

void merge(int a[], int l, int m, int r)

int temp[100]; // temporary array (max size 100)

int i = l, j = m + 1, k = l;

while (i <= m && j <= r)

if (a[i] <= a[j])

temp[k++] = a[i++];

else

temp[k++] = a[j++];

while (i <= m) temp[k++] = a[i++];

while (j <= r) temp[k++] = a[j++];

for (int x = l; x <= r; x++)

a[x] = temp[x];

void mergeSort(int a[], int l, int r)

if (l < r)
{

int m = (l + r) / 2;

mergeSort(a, l, m);

mergeSort(a, m + 1, r);

merge(a, l, m, r);

int main()

int a[] = {5, 2, 9, 1, 6};

int n = 5;

mergeSort(a, 0, n - 1);

cout << "Sorted array: ";

for (int i = 0; i < n; i++)

cout << a[i] << " ";

return 0;

You might also like