answersLogoWhite

0

The following template function will sort an array of any type using the merge sort algorithm, non-recursively. Note that you must call the function by passing a pointer to the array, rather than passing the array by reference as you normally would with sorting algorithms. This is because the function uses a second array (a work array) of the same size to perform the actual merge, switching from one to the other upon each iteration, so there's no guarantee the final sorted array will be the one you originally referred to (it could be the work array). You could maintain a count of the iterations and perform an extra copy of the work array back to your referenced array if the count is odd, but it's more efficient to simply return the sorted array through a pointer.

The code can be difficult to follow if you're not familiar with the merge sort algorithm, so I've commented the code verbosely to explain what's going on. In essence, we're treating the original array as being several subsets of 1 element each. A subset of 1 is already sorted, so we simply merge these subsets in pairs, so the new array contains sorted subsets of 2 elements each. We repeat the process, merging each pair of subsets to create sorted subsets of 4, then 8 and so on, until there is only 1 sorted subset in the array. When we merge two subsets into one, we simply compare the first element of each subset and place the lowest into the merged subset.

Note that in the final iteration, the second subset of the pair may be smaller than the first, or it may not exist at all (in which case the remaining subset may be smaller). However, the merge algorithm caters for this eventuality quite efficiently. If there's only one subset remaining (which can happen during any iteration as elements are removed from the subsets and merged into the work array), the remaining elements are simply copied sequentially from that subset since they will already be in order (as determined by the previous iteration).

template<typename T>

void merge_sort(T* A[], size_t size)

{

// Arrays of length 0 or 1 are already sorted.

if( size < 2 )

return;

// Instantiate a new array of the same size as A.

T *B = new T[size];

// Array A initially contains subsets of width 1 element, then 2, 4, 8...

for( size_t width=1; width<size; width<<=1 )

{

// Dereference A (now known as C).

T *C = *A;

// Array B initially holds subsets of width 2 elements, then 4, 8, 16...

size_t width2 = 2*width;

// Iterate through each pair of subsets in C...

// sub1 is the start index of the first subset of the pair in C.

for( size_t sub1=0; sub1<size; sub1+=width2 )

{

// sub2 is the start index of the second subset of the pair in C.

size_t sub2 = min( sub1+width, size );

// next is the start of the next pair of subsets in C.

size_t next = min( sub1+width2, size );

// Start with the first elements in each pair of subsets in C

// (the ones with the lowest values in each subset).

size_t c1 = sub1;

size_t c2 = sub2;

// Iterate through B's elements from index [sub1] to index [next-1].

for( size_t b=sub1; b<next; ++b )

// Copy the lowest of the two indexed values in C to B.

B[b] = ( c1<sub2 && ( c2>=next C[c1]<=C[c2] )) ? C[c1++] : C[c2++];

}

// Swap the roles of *A and B (note that C still points to the dereferenced A at this point).

*A=B; B=C;

}

// Finished with B (*A is now the fully-sorted array).

delete[]B;

}

User Avatar

Wiki User

11y ago

What else can I help you with?

Continue Learning about Engineering

CAn you work in c or c plus plus without editor?

You can compile, link and execute programs without text-editor.


Can you use c in c plus plus without using class and object?

Sure.


What are the conditions to swap in c plus plus without temporary?

You can swap two integers without temporary storage by bitwise exclusive-or'ing them in a specific sequence...a ^= b;b ^= a;a ^= b;


What are the advantages of the recursion in c plus plus?

Any problem that can be solved by dividing the problem into smaller problems of the same type is a good candidate for recursion. However, there are actually very few applications that cannot be resolved more efficiently with an iterative loop. It therefore pays to know when recursion is unavoidable and when it is optional. The main benefit to recursion is that each instance of the function maintains its own set of non-static local variables completely independently of all other instances. But if these variables are of no use to the function when a recursive call returns, then an iterative implementation would be more efficient. Function calls are expensive in terms of memory consumption and performance, so the fewer we make, the better. A classic example of recursive application is the quicksort algorithm. In simple terms, quicksort is a function that accepts a subset of data. The data is usually stored in an array and the function accepts the left and right index of the subset to be sorted. Initially this will be lower and upper bounds of the entire array, but if the indices indicate a subset with fewer than 2 items, the function immediately exits. This effectively defines the return path from the recursions. Assuming there are 2 or more items, the function selects one of the items (the pivot) and then sorts the array such that items less than the pivot are placed to its left, and items greater or equal to its right. This moves the pivot into its final position, but the items on either side may still be unsorted. Thus the function calls itself twice, once for each of these subsets, which gradually reduces the problem down into smaller and smaller subsets until a subset has fewer than 2 items, at which point the recursion unwinds to the previous instance. Recursion is required because when the first recursive call returns, the subset to the left of the pivot is guaranteed to be sorted, but the subset to the right is not. This means we must maintain local variables in order to determine the lower and upper bounds of that subset. Although quicksort is an elegant application of recursion, there is still room for improvement. Firstly, it is better to make a recursive call upon the smaller of the two subsets. The smaller the subset, the fewer recursions that will be incurred sorting it. Secondly, since the second recursion is also the last statement in the function, there is no need to maintain the local variables when it returns. Thus the second recursion can be implemented as a tail call. This effectively means we modify the existing local variables to suit and then recall the same instance (with a goto). This reduces the depth of recursion by one function call per recursion which will quickly add up to a significant boost in efficiency.


C plus plus code to find the length of a string without using function?

int i = 0; while(str[i] != NULL){ i++; }

Related Questions

What are the steps to execute a c plus plus programme?

Build it, link it, run it.


Make programme for multification of three no in c plus plus?

result = a * b * c;


How do you make merge?

If you want to merge the cell information with the cell information then basic maths operators like Plus, Minus, Subtract, Divide do work using the formular bar.


How do you write a programme to print a plus bi in c plus plus?

#include &lt;iostream&gt; int main() { std::cout &lt;&lt; "a plus bi" &lt;&lt; std::endl; return 0; }


Write a c plus plus programme to illustrate single inheritance?

struct A {}; // base class struct B : A {} // derived class (single inheritance).


Write a programme to find greater among two numbers in c plus plus?

You could use an if, but the ternary operator is especially compact for this purpose: result = a &gt; b ? a : b;


Can a user compile c programme using c plus plus compiler?

Usually, but not always. For example the following is legal in C, but illegal in C++: char new [3] = "ABC";


What is the scrap value of a 747?

According to the TV programme MEGA STRUCTURES 747 DEMOLITION $3.5million plus 12 weeks to dismantle.


Is you can not learn the .net without the knowledge of c and c plus plus?

You is can.


What is 123a plus 564d plus 764x plus 6677583n?

6679034adxn ( i did it without a calculator as well)


CAn you work in c or c plus plus without editor?

You can compile, link and execute programs without text-editor.


What is 23 plus 6 plus 25 plus 8 plus 16 equals?

78 - without the aid of a calculator !