Last active
May 17, 2024 18:04
-
-
Save shitu13/a8dee65d210d12921772d095eac8b134 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
class Solution | |
{ | |
public: | |
void merge(int arr[], int l, int m, int r) | |
{ | |
int n1 = m-l+1; | |
int n2 = r-m; | |
int L[n1], R[n2]; | |
int k =l; | |
for(int i=0; i<n1; i++){ | |
L[i] = arr[k++]; | |
} | |
for(int i=0; i<n1; i++){ | |
R[i] = arr[k++]; | |
} | |
int i =0; | |
int j =0; | |
k = l; | |
while(i<n1 && j<n2){ | |
if(L[i]<= R[j]){ | |
arr[k++] = L[i++]; | |
}else{ | |
arr[k++] = R[j++]; | |
} | |
} | |
while(i<n1){ | |
arr[k++] = L[i++]; | |
} | |
while(j<n2){ | |
arr[k++] = R[j++]; | |
} | |
} | |
public: | |
void mergeSort(int arr[], int l, int r) | |
{ | |
if(l>=r){ | |
return; | |
} | |
int m = l+ (r-l)/2; | |
mergeSort(arr, l, m); | |
mergeSort(arr, m+1, r); | |
merge(arr, l, m, r); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
GeeksForGeeks