Thread: Merge sort (sorted arrays)

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Apr 2007
    Location
    Greece
    Posts
    52
    Indeed. I don't want to modify the original array because I have use of them as they are.
    The point that I have 5 arrays. If I construct the big sorted array using pointers, I need 4 times to do merge. Is it more efficient to use the implementation of the arrays of pointer 4 times or is it better to copy the values each time into one array with the sum of the sizes of the two initial arrays?

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    You simply want a k-way merge. Here is some sample code for how to implement that (untested):
    Code:
    //Inputs a .. e
    const object a[42]; // can be any length
    //...
    const object e[1337]; // can be any length
    
    //Output
    object *out[42+...+1337];
    
    struct Inputs {
        object *ptr;
        int count;
        bool operator < (const Inputs & b) { return *ptr < *(b.ptr); }
    };
    
    //Setup
    Inputs in[5];
    int alive = 5, idx = 0;
    in[0].ptr = a; in[0].count = 42;
    //...
    in[4].ptr = e; in[4].count = 1337;
    
    while (alive > 0)
    {
        //TODO: Insert basic algorithm here, to sort 'alive' items in array 'in'
        //by what their 'ptr' points to e.g. std::sort(in[0], in[5]);
    
        out[idx++] = in[0].ptr++;
        if (--in[0].count == 0)
            in[0] = in[--alive];
    }
    //Done: output is in the 'out' array.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Merge Sort
    By Echooo in forum C++ Programming
    Replies: 2
    Last Post: 03-15-2006, 03:16 PM
  2. Quick Sort or Merge Sort???
    By swanley007 in forum C++ Programming
    Replies: 6
    Last Post: 11-10-2005, 06:48 PM
  3. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 12:09 PM
  4. Merge Sort using a linked list
    By EvenFlow in forum C Programming
    Replies: 0
    Last Post: 10-04-2001, 11:07 PM
  5. merge sort
    By Unregistered in forum C Programming
    Replies: 0
    Last Post: 09-02-2001, 06:58 PM