From fa7043e135e8ac2a98e0a918602d3350b3573f14 Mon Sep 17 00:00:00 2001 From: Sameer Bhardwaj Date: Tue, 25 Jun 2019 04:05:00 +0530 Subject: [PATCH] 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 cpp --- .../sorting-algorithms/merge-sort/index.md | 86 +++++++++++++------ 1 file changed, 58 insertions(+), 28 deletions(-) diff --git a/guide/english/algorithms/sorting-algorithms/merge-sort/index.md b/guide/english/algorithms/sorting-algorithms/merge-sort/index.md index b2da96a882..aa5ff11e57 100644 --- a/guide/english/algorithms/sorting-algorithms/merge-sort/index.md +++ b/guide/english/algorithms/sorting-algorithms/merge-sort/index.md @@ -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 log2n 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,34 +178,64 @@ 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. +```cpp +void merge(int arr[], int l, int m, int r) +{ + int i, j, k; + int n1 = m - l + 1; + int n2 = r - m; + int L[n1], R[n2]; + + 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++; + } +} -```c++ -void mergesort(int A[],int size_a,int B[],int size_b,int C[]) -{ - int token_a,token_b,token_c; - for(token_a=0, token_b=0, token_c=0; token_a