Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Merge sort Exercise: Sort a collection of integers using the Merge sort

C++ Sorting: Exercise-10 with Solution

Write a C++ program to sort a collection of integers using the Merge sort.

Sample Solution:

C++ Code :

#include<iostream>
using namespace std;
void Merge(int* A,int,int,int);
void Merge_Sort(int* A,int p,int r);
int main()
{   
  int a[] = {125, 0, 695, 3, -256, -5, 214, 44, 55};
  int len = 9;
  cout << "Original numbers:\n";
  for(int i=0; i<len; i++) {
        cout << a[i] << " ";
    }
   
    Merge_Sort(a,0,len-1);
    cout << "\nSorted numbers:\n";
    for(int i=0; i<len; i++) {
        cout << a[i] << " ";
    }
    return 0;
}
void Merge(int* arr,int p,int q,int r) {
    int n1=q-p+1;
    int n2=r-q;
    int L[n1+1];
    int R[n2+1];
    for(int i=0; i<n1; i++) L[i]=arr[p+i];
    for(int j=0; j<n2; j++) R[j]=arr[q+1+j];
    int i=0;
    int j=0;
    int n=0;
    while(i!=n1 && j!=n2) {
        if(L[i]>R[j]) {
            arr[p+n]=R[j];
            j++;
        } else {
            arr[p+n]=L[i];
            i++;
        }
        n++;
    }
    while(j!=n2) {
        arr[p+n]=R[j];
        j++;
        n++;
    }
    while(i!=n1) {
        arr[p+n]=L[i];
        i++;
        n++;
    }
}
void Merge_Sort(int* arr,int p,int r) {
    if(r>p) {
        int q;
        q=(p+r)/2;
        Merge_Sort(arr,p,q);
        Merge_Sort(arr,q+1,r);
        Merge(arr,p,q,r);
    }
}

Sample Output:

Original numbers:
125 0 695 3 -256 -5 214 44 55 
Sorted numbers:
-256 -5 0 3 44 55 125 214 695 

Flowchart:

Flowchart: Sort a collection of integers using the Merge sort

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to sort an array of elements using the Insertion sort algorithm.
Next: Write a C++ program to sort a collection of integers using the Pancake sort.

What is the difficulty level of this exercise?