diff options
Diffstat (limited to 'Random/mergesort.cpp')
-rw-r--r-- | Random/mergesort.cpp | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/Random/mergesort.cpp b/Random/mergesort.cpp new file mode 100644 index 0000000..82bd33b --- /dev/null +++ b/Random/mergesort.cpp @@ -0,0 +1,49 @@ +#include <bits/stdc++.h>
+using namespace std;
+
+
+void merge(int *A, int p, int q, int r){
+ int n1 = q - p + 1;
+ int n2 = r - q;
+ int L[n1];
+ int R[n2];
+
+ for(int i = 0; i<n1; ++i)
+ L[i] = A[p+i];
+ for(int j = 0; j<n2; ++j)
+ R[j] = A[q+1+j];
+
+ int i = 0, j = 0;
+
+ for(int k = p; k <= r; ++k){
+ if(L[i] <= R[j] && i < n1){
+ A[k] = L[i];
+ ++i;
+ }else{
+ A[k] = R[j];
+ ++j;
+ }
+ }
+
+}
+void merge_sort(int *A, int p, int r){
+ if(p<r){
+ int q = (p+r)/2;
+ merge_sort(A, p, q);
+ merge_sort(A, q+1, r);
+ merge(A, p, q, r);
+ }
+}
+
+int main(){
+
+ int A[10]={9,8,7,6,5,4,3,2,1,0};
+ int p = 0, r = 9;
+ merge_sort(A, p, r);
+
+ for(int i = 0; i < r+1; ++i)
+ printf("%d|", A[i]);
+
+ cout << "\n";
+ return 0;
+}
\ No newline at end of file |