Skip to content

Latest commit

 

History

History
51 lines (46 loc) · 1.14 KB

File metadata and controls

51 lines (46 loc) · 1.14 KB

#Merge Sort Practice

vector<int> merge(vector<int> &left,vector<int>& right)
    {
        int a=0;
        int b=0;
        vector<int> temp;
        while(a<left.size() && b<right.size())
        {
            if(left[a]<right[b])
            {
                temp.push_back(left[a]);
                a++;
            }
            else
            {
                temp.push_back(right[b]);
                b++;
            }
        }

        while(a<left.size() )
        {
            temp.push_back(left[a]);
            a++;
        }
        while(b<right.size() )
        {
            temp.push_back(right[b]);
            b++;
        }

        return temp;
    }
    vector<int> mergesort(vector<int>& v)
    {
        if(v.size()<=1)
            return v;

        int mid=v.size()/2;
        vector<int> left(v.begin(),v.begin()+mid);
        vector<int> right(v.begin()+mid,v.end());
        left=mergesort(left);
        right=mergesort(right);
        return merge(left,right);
    }
    vector<int> sortArray(vector<int>& v) {
        
        return mergesort(v);
    }