Sort an array A using Merge Sort. Change in the input array itself. So no need to return or print anything.

TITLE:-Merge Sort Code
PROBLEM:-

Sort an array A using Merge Sort.

Change in the input array itself. So no need to return or print anything.

Input format :
Line 1 : Integer n i.e. Array size
Line 2 : Array elements (separated by space)
Output format :
Array elements in increasing order (separated by space)
Constraints :
1 <= n <= 10^3
Sample Input 1 :
6 
2 6 8 5 4 3
Sample Output 1 :
2 3 4 5 6 8
Sample Input 2 :
5
2 1 5 2 3
Sample Output 2 :
1 2 2 3 5 

SOLUTION:-

#include <iostream>
using namespace std;
void mergeSort(int a[], int size){
	// Write your code here
    if(size==0||size==1)
        return;
    int mid=size/2;
  /*if(size%2==0)
    {
      mergeSort(a,mid);  
      mergeSort(a+mid,mid);
    }
    else{
        mergeSort(a,mid);
        mergeSort(a+mid,mid+1);
    }*/
    for(int i=0;i<mid;i++)
        for(int j=mid;j<size;j++)
        {
            if(a[i]>a[j])
            {
                int temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
      if(size%2==0)
    {
      mergeSort(a,mid);  
      mergeSort(a+mid,mid);
    }
    else{
        mergeSort(a,mid);
        mergeSort(a+mid,mid+1);
    }
}


int main() {
  int length;
  cin >> length;
  int* input = new int[length];
  for(int i=0; i < length; i++)
    cin >> input[i];
  mergeSort(input, length);
  for(int i = 0; i < length; i++) {
    cout << input[i] << " ";
  }
}

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *