Merge Sort in non-increasing order - C++
Tue Mar 04 2025 01:13:04 GMT+0000 (Coordinated Universal Time)
Saved by
@Rohan@99
#include <iostream>
#include <vector>
using namespace std;
void Merge(int a[], int low, int mid, int high)
{
vector<int> temp;
int i = low, j = mid+1;
while(i <= mid && j <= high)
{
if(a[i] >= a[j])
{
temp.push_back(a[i]);
++i;
}
else
{
temp.push_back(a[j]);
++j;
}
}
while(i <= mid)
{
temp.push_back(a[i]);
++i;
}
while(j <= high)
{
temp.push_back(a[j]);
++j;
}
for(int i = low; i <= high; ++i)
a[i] = temp[i-low];
}
void MergeSort(int a[], int low, int high)
{
if(low == high)
return;
int mid = (low+high) / 2;
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);
Merge(a, low, mid, high);
}
int main()
{
int n;
cin >> n;
int a[n];
for(int i = 0; i < n; ++i)
cin >> a[i];
MergeSort(a, 0, n-1);
for(int i = 0; i < n; ++i)
cout << a[i] << " ";
return 0;
}
content_copyCOPY
Comments