Merge Sort

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int a[N];

void merge(int l, int r, int mid){
    // the function after getting two sorted arrays and combine them

    // size of the two sub arrays
    int l_size = mid - l + 1;
    int r_size = r - mid;

    int L[l_size + 1];
    int R[r_size + 1];

    // give last idx = infinity
    L[l_size] = INT_MAX;
    R[r_size] = INT_MAX;

    // copy values to the sub arrays
    for(int i=0;i<l_size;i++){
        L[i] = a[i + l];
    }
    for(int i=0;i<r_size;i++){
        R[i] = a[i + mid + 1];
    }

    // now again copy the sorted values by comparing(those two) to the original array using two pointers on the subarrays
    int l_i = 0;
    int r_i = 0;

    for(int i=l;i<=r;i++){
        if(L[l_i] > R[r_i]){
            a[i] = R[r_i];
            r_i++;
        }else{
            a[i] = L[l_i];
            l_i++;
        }
    }

}

void mergeSort(int l, int r){
    // the fucntion breaks the original array into two sorted arrays and then merge with the help of above function.
    // break by mid then recursively sort the two halves.

    if(l == r) return;
    int mid = (l+r)/2;
    mergeSort(l, mid);
    mergeSort(mid+1, r);
    merge(l, r, mid);
}

int main(){
    // write code here
    for(int i=0;i<5;i++){
        cin >> a[i];
    }
    
    mergeSort(05-1);
    for(int i=0;i<5;i++){
        cout << a[i] << " ";
    }

    return 0;
}

Output
Clean veiw



Comments

Popular Posts