Completed c++ implemetation (#25547)
* Completed c++ implemetation c++ implementation contained only merge function(by the name of merge sort). Completed the implementation by providing both divide and merge functions. * fix: add triple backticks for c# code * fix: changed csharp to cpppull/27052/head^2
parent
e9fbe95454
commit
fa7043e135
|
@ -23,7 +23,7 @@ T(n) = 2T(n/2) + n
|
|||
|
||||
Counting the number of repetitions of n in the sum at the end, we see that there are lg n + 1 of them. Thus the running time is n(lg n + 1) = n lg n + n. We observe that n lg n + n < n lg n + n lg n = 2n lg n for n>0, so the running time is O(n lg n). Another simple way to remember the time complexity O(n lg n) of merge sort is that it takes roughly log<sub>2</sub><sup>n</sup> steps to split an array of size n to multiple arrays of size one. After each split, the algorithm have to merge 2 sorted arrays into one which can take n steps in total. As a result, the time complexity for merge sort is O(n lg n).
|
||||
|
||||
```Algorithm
|
||||
```
|
||||
MergeSort(arr[], left, right):
|
||||
If right > l:
|
||||
1. Find the middle point to divide the array into two halves:
|
||||
|
@ -178,33 +178,63 @@ int main()
|
|||
|
||||
```
|
||||
### Implementation in C++
|
||||
|
||||
Let us consider array A = {2,5,7,8,9,12,13}
|
||||
and array B = {3,5,6,9,15} and we want array C to be in ascending order as well.
|
||||
|
||||
```c++
|
||||
void mergesort(int A[],int size_a,int B[],int size_b,int C[])
|
||||
```cpp
|
||||
void merge(int arr[], int l, int m, int r)
|
||||
{
|
||||
int token_a,token_b,token_c;
|
||||
for(token_a=0, token_b=0, token_c=0; token_a<size_a && token_b<size_b; )
|
||||
{
|
||||
if(A[token_a]<=B[token_b])
|
||||
C[token_c++]=A[token_a++];
|
||||
else
|
||||
C[token_c++]=B[token_b++];
|
||||
}
|
||||
int i, j, k;
|
||||
int n1 = m - l + 1;
|
||||
int n2 = r - m;
|
||||
int L[n1], R[n2];
|
||||
|
||||
if(token_a<size_a)
|
||||
{
|
||||
while(token_a<size_a)
|
||||
C[token_c++]=A[token_a++];
|
||||
}
|
||||
else
|
||||
{
|
||||
while(token_b<size_b)
|
||||
C[token_c++]=B[token_b++];
|
||||
}
|
||||
for (i = 0; i < n1; i++)
|
||||
L[i] = arr[l + i];
|
||||
for (j = 0; j < n2; j++)
|
||||
R[j] = arr[m + 1+ j];
|
||||
|
||||
i = 0;
|
||||
j = 0;
|
||||
k = l;
|
||||
while (i < n1 && j < n2)
|
||||
{
|
||||
if (L[i] <= R[j])
|
||||
{
|
||||
arr[k] = L[i];
|
||||
i++;
|
||||
}
|
||||
else
|
||||
{
|
||||
arr[k] = R[j];
|
||||
j++;
|
||||
}
|
||||
k++;
|
||||
}
|
||||
|
||||
while (i < n1)
|
||||
{
|
||||
arr[k] = L[i];
|
||||
i++;
|
||||
k++;
|
||||
}
|
||||
|
||||
while (j < n2)
|
||||
{
|
||||
arr[k] = R[j];
|
||||
j++;
|
||||
k++;
|
||||
}
|
||||
}
|
||||
|
||||
void mergeSort(int arr[], int l, int r)
|
||||
{
|
||||
if (l < r)
|
||||
{
|
||||
int m = l+(r-l)/2;
|
||||
|
||||
mergeSort(arr, l, m);
|
||||
mergeSort(arr, m+1, r);
|
||||
|
||||
merge(arr, l, m, r);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
|
Loading…
Reference in New Issue