diff --git a/Competitive Coding/Sorting/Merge_Sort/Merge_Sort.c b/Competitive Coding/Sorting/Merge_Sort/Merge_Sort.c index 02cdabd67..fd251bd8d 100644 --- a/Competitive Coding/Sorting/Merge_Sort/Merge_Sort.c +++ b/Competitive Coding/Sorting/Merge_Sort/Merge_Sort.c @@ -1,65 +1,85 @@ -/* Merge sort in C */ -#include -#include - -// Function to Merge Arrays L and R into A. -// lefCount = number of elements in L -// rightCount = number of elements in R. -void Merge(int *A,int *L,int leftCount,int *R,int rightCount) { - int i,j,k; - - // i - to mark the index of left aubarray (L) - // j - to mark the index of right sub-raay (R) - // k - to mark the index of merged subarray (A) - i = 0; j = 0; k =0; - - while(i + using namespace std; + +void merge(int arr[], int l, int m, int r) { + int i = l; + int j = m + 1; + int k = l; + + /* create temp array */ + int temp[5]; + + while (i <= m && j <= r) { + if (arr[i] <= arr[j]) { + temp[k] = arr[i]; + i++; + k++; + } else { + temp[k] = arr[j]; + j++; + k++; + } + + } + + /* Copy the remaining elements of first half, if there are any */ + while (i <= m) { + temp[k] = arr[i]; + i++; + k++; + + } + + /* Copy the remaining elements of second half, if there are any */ + while (j <= r) { + temp[k] = arr[j]; + j++; + k++; + } + + /* Copy the temp array to original array */ + for (int p = l; p <= r; p++) { + arr[p] = temp[p]; + } } - -// Recursive function to sort an array of integers. -void MergeSort(int *A,int n) { - int mid,i, *L, *R; - if(n < 2) return; // base condition. If the array has less than two element, do nothing. - - mid = n/2; // find the mid index. - - // create left and right subarrays - // mid elements (from index 0 till mid-1) should be part of left sub-array - // and (n-mid) elements (from mid to n-1) will be part of right sub-array - L = (int*)malloc(mid*sizeof(int)); - R = (int*)malloc((n- mid)*sizeof(int)); - - for(i = 0;i> myarray[i]; + } + cout << "Before Sorting" << endl; + for (int i = 0; i < 5; i++) { + cout << myarray[i] << " "; + } + cout << endl; + mergeSort(myarray, 0, (arr_size - 1)); // mergesort(arr,left,right) called + + cout << "After Sorting" << endl; + for (int i = 0; i < 5; i++) { + cout << myarray[i] << " "; + } + + return 0; }