SUPER IMPORTANT: MERGESORT - O(nlogn)

 #include <iostream>

using namespace std;

void merge(int* arr, int first, int mid, int last){

    int b[50];

    int i,j,k;

    i=first;

    j=mid+1;

    k=first;

    while(i<=mid && j<=last){

        

        if (arr[i]<=arr[j]){

            b[k++]=arr[i++];

        }

        else

            b[k++]=arr[j++];

    }

    if(i>mid){

        while(j<=last)

            b[k++]=arr[j++];

    }

    else {

        while(i<=mid)

            b[k++]=arr[i++];

    }

        

    

    for (int i=first;i<=last;i++){

        arr[i]=b[i];

    }

}

void mergesort(int *arr, int first, int last){

    int mid;

    if(first<last){

        mid=(first+last)/2;

        mergesort(arr,first,mid);

        mergesort(arr,mid+1,last);

        merge(arr,first,mid,last);

    }

}


int main() {

    int arr[5]={2,3,1,2,3};

    mergesort(arr, 0, 5);

    for(int i=0;i<5;i++){

        cout<<arr[i]<<endl;

    }


    return 0;

}

Comments

Popular posts from this blog

Sum of Even Numbers till N

Find the Runner-Up Score!

Print All Substrings