-3
\$\begingroup\$

Will this code actually work as MergeSort? This is working to sort the array but is it MergeSort?

My faculty did approve of this but he probably did not see the code properly and I need some serious help here.

#include<iostream>
using namespace std;
int mid;
int array[8]={98, 23, 45, 14, 6, 67, 33};

void msort(int s, int e)
{
if (s<e) {
    mid = (s + e) / 2;
    msort(s, mid);
    msort(mid + 1, e);

}

for(int i=s;i<=e;++i)
{
    for(int j=i+1;j<=e;++j)
    {
        if(array[i]>array[j])
        {
            array[i] = array[i]+array[j];
            array[j] = array[i]-array[j];
            array[i] = array[i]-array[j];
        }
    }
}
}

int main() {
msort(0, 7);

for (int i=0; i<8; i++)
{
    cout<<"\t"<<a[i];
}
}
\$\endgroup\$
1
\$\begingroup\$

No it is not. The merge phase of the merge sort shall not be quadratic (it is linear for the external merge and linearithmic for in-place one).

In your code, the merge phase fails to account for the fact that left and right subarrays are already sorted, and degenerates into bubble sort.

As a side note I highly advise against the way you swap elements.

\$\endgroup\$
  • \$\begingroup\$ So is this basically a bubble sort? Then how is the result coming accurate even though the sort happens inside the msort functions and I'm passing the values s and e which are being modified by mid? \$\endgroup\$ – Avi Seth Nov 2 '17 at 20:37
  • \$\begingroup\$ Also, the swapping method is bad i know, was just trying it for fun. \$\endgroup\$ – Avi Seth Nov 2 '17 at 20:38
  • 1
    \$\begingroup\$ @AviSeth You complexity will be O(n² log n). Worse than bubble \$\endgroup\$ – ratchet freak Nov 3 '17 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.