TITLE:-Merge Sort Code
PROBLEM:-
Sort an array A using Merge Sort.
Line 1 : Integer n i.e. Array size
Line 2 : Array elements (separated by space)
Array elements in increasing order (separated by space)
Constraints :
1 <= n <= 10^3
6
2 6 8 5 4 3
Sample Output 1 :
2 3 4 5 6 8
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] << " ";
}
}