Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8947317
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T12:43:43+00:00 2026-06-15T12:43:43+00:00

I am trying to make a merge sort algorithm with the stl library but

  • 0

I am trying to make a merge sort algorithm with the stl library but am having some issues. Below is the code I am using

template <typename Item, typename SizeType>
void merge_sort(Item array[], SizeType size){
    size_t n1; //Size of the first subarray
    size_t n2; //Size of the second subarray

    if(size > 1){
        //Compute the size of the subarrays
        n1 = size/2;
        n2 = size - n1;

        //create the temp array.
        int* n1Temp = new int[n1];
        int* n2Temp = new int[n2];
        int i;
        for(i = 0; i < n1; i++)
            n1Temp[i] = array[i];
        for(i = 0; i < n2; i++)
            n2Temp[i] = array[i + n1];

        //recursive calls
        merge_sort(n1Temp, n1);//sort from array[0] through array[n1 - 1] 
        merge_sort(n2Temp, n2);//sort from array[n1] to the end

        //Merge the two sorted halves.
        vector<int> v(array, array + size);
        merge(n1Temp, n1Temp + n1, n2Temp, n2Temp + n2, v.begin());     
        copy(v.begin(), v.end(), array);//copy the vector back to the array

        delete[] n1Temp;
        delete[] n2Temp;
    }
}

The code sorts fine but the problem is that it acts like a O(n^2) algorithm instead of O(n \log n), which is due to the creation of the vector in each merge sort call (I think). I tried removing the vector and just using an array in the merge function which can be seen below

    //Merge the two sorted halves.
    int* finalArray = new int[n1 + n2];
    merge(n1Temp, n1Temp + n1, n2Temp, n2Temp + n2, begin(finalArray)); 
    array = finalArray;

But this gets me nothing but errors. Is there any thing I can do to salvage my merge sort algorithm?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T12:43:44+00:00Added an answer on June 15, 2026 at 12:43 pm

    As both Vaughn and user93353 pointed out, you should be able to merge directly into the target array at each merge-point. But you can still use std::vector<> to make this significantly easier on yourself.

    Also, your temp arrays are of direct type ‘int’, and I’m fairly sure that was intended to be the type of the template parameter Item. I’m not sure what the SizeType parameter is for, but I left it in case you had special ideas for it. Whatever it is, it better be compatible with size_t :

    template <typename Item, typename SizeType>
    void merge_sort(Item array[], SizeType size)
    {
        if(size > 1)
        {
            //Compute the size of the subarrays
            size_t n1 = size/2;
    
            //create the temp array
            std::vector<Item> n1Temp(array, array+n1);
            std::vector<Item> n2Temp(array+n1, array+size);
    
            //recursive calls
            merge_sort(&n1Temp[0], n1);       //sort array[0] through array[n1-1]
            merge_sort(&n2Temp[0], size-n1);  //sort array[n1] through array[size-1]
    
            // merge the sorted halves
            std::merge(n1Temp.begin(), n1Temp.end(),
                       n2Temp.begin(), n2Temp.end(), array);
        }
    }
    

    The above technique splits the sub-sequences top-down via copy, then merges in-place the split-copies into the original array. You can reduce this algorithm by one sublist allocation time (but no less space) by doing the splits on the original array, then merging into temp-space and copying after, which i think you were trying to do in the first place:

    template <typename Item>
    void merge_sort(Item ar[], size_t n)
    {
        if (n > 1)
        {
            // Compute the size of the subarrays
            size_t n1 = n/2;
    
            // invoke recursion on the submerges
            merge_sort(ar, n1);      //sort array[0] through array[n1-1]
            merge_sort(ar+n1, n-n1); //sort array[n1] through array[size-1]
    
            // create merge-buffer
            std::vector<Item> mrg;
            std::merge(ar, ar+n1, ar+n1, ar+n, back_inserter(mrg));
            std::copy(mrg.begin(), mrg.end(), ar);
        }
    }
    

    General Iterator-Based Solution

    For a general solution that allows even more flexibility you can define your merge-sort based on iterators rather than Item pointers. It gets a little more hairy, but the benefits are very std-lib-ish.

    template <typename Iterator>
    void merge_sort(Iterator first, Iterator last)
    {
        typedef typename std::iterator_traits<Iterator>::value_type value_type;
        typedef typename std::iterator_traits<Iterator>::difference_type difference_type;
    
        difference_type n = std::distance(first, last)/2;
        if (n == 0)
            return;
    
        // invoke recursion on the submerges
        merge_sort(first, first + n);
        merge_sort(first + n, last);
    
        // create merge-buffer
        std::vector<value_type> mrg(std::distance(first, last));
        std::merge(first, first+n, first+n, last, mrg.begin());
        std::copy(mrg.begin(), mrg.end(), first);
    }
    

    Finally, if you find yourself sorting a ton of fixed-length C-arrays you may find the following helpful (it uses the general-iterator solution above):

    // front-loader for C arrays
    template<typename Item, size_t N>
    void merge_sort(Item (&ar)[N])
    {
        merge_sort(std::begin(ar), std::end(ar));
    }
    

    It make the following code rather convenient:

    int arr[1024];
    ... fill arr ...
    merge_sort(arr);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to make a merge sort method, but it keeps on giving
I'm trying to merge two branches together using mercurial and there are some conflicts.
Trying to make a small countdown timer in my app but it's not working.
I'm trying to make logging for my rails app and have some dilemmas over
I'm trying merge a large group of images onto a new background but I
I am trying to merge some contents from table1 and table2 into another table3
I'm trying to make sense of a puzzling behavior with git union merge. To
I am struggling trying to make sense of using the Git subtree strategy. My
I have been trying to optimize some code which handles raw pixel data. Currently
I am trying to learn to simplify my code and merge multiple data.frames (>2)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.