- //merge the A[s...m] and A[m+1...t] to R[s...t]
- template<typename typeT>
- void two_merge(typeT A[], typeT R[], int s, int m, int t)
- {
- int i, j, k;
- i = s;
- j = m+1;
- k = s;
- while(i <=m && j <= t)
- {
- if(A[i] <= A[j])
- R[k++] = A[i++];
- else R[k++] = A[j++];
- }
- while(i <= m)
- R[k++] = A[i++];
- while(j <= t)
- R[k++] = A[j++];
- }
- //merge the A[0...n-1]'s sub len to B[].
- template<typename typeT>
- void merge_pass(typeT A[], typeT B[], int n, int len)
- {
- int p = 0;
- while(p + 2*len-1 <= n-1)
- {
- two_merge(A, B,p, p+len - 1, p+2*len-1);
- p += 2*len;
- }
- if(p + len -1 <= n-1)//the two sub len not equal
- two_merge(A, B, p, p+len-1, n-1);
- else
- for(; p <= n-1; ++p)
- B[p] = A[p];
- }
- template<typename typeT>
- void merge_sort(typeT A[], int n)
- {
- typeT *B = new typeT[n];
- int len = 1;
- while(len < n)
- {
- merge_pass(A, B, n, len);
- len *= 2;
- merge_pass(B, A, n, len);
- len *= 2;
- }
- delete []B;
- }
归并排序(Merge sort)
最新推荐文章于 2022-11-17 18:56:06 发布