Created
March 9, 2016 03:53
-
-
Save ahmedengu/d84b82895167c1ca1e4c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
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++; | |
} | |
} | |
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); | |
} | |
} | |
void print(int A[], int size) | |
{ | |
int i; | |
for (i=0; i < size; i++) | |
cout<<A[i]<<((i==size-1)?"":" ,"); | |
} | |
int main() | |
{ | |
int arr[] = {1,5,7,8,9,4,5,6,7,8}; | |
int arr_size = 10; | |
mergeSort(arr, 0, arr_size - 1); | |
print(arr, arr_size); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment