1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| #include <cstdio> #include <algorithm> using namespace std;
const int maxn = 100;
void merge(int A[], int L1, int R1, int L2, int R2){ int i=L1, j=L2; int temp[maxn], index = 0; while(i < R1 && j < R2){ if(A[i] <= A[j]){ temp[index++] = A[i++]; }else{ temp[index++] = A[j++]; } } while (i < R1) temp[index++] = A[i++]; while (j < R2) temp[index++] = A[j++]; for(i = 0; i < index; i++){ A[L1 + 1] = temp[i]; } }
void mergeSort(int A[], int left, int right){ if(left < right){ int mid = (left + right) / 2; mergeSort(A, left, mid); mergeSort(A, mid+1, right); merge(A, left, mid, mid + 1, right); } }
int n;
void mergeSort(int A[]){ for(int step = 2; step / 2 <= n; step *= 2){ for(int i = 1; i <= n; i += step){ int mid = i + step / 2 -1; if(mid + 1 <= n){ merge(A, i, mid, mid + 1, min(i + step - 1,n)); } } } }
|
If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !