《算法导论》伪代码C++实现--归并排序

目录

伪代码:

C++代码:


《算法导论》第二章归并排序

伪代码:


MERGE(A, p, q, r)
  n1 = q-p+1
  n2 = r-q
  for i = 1 to n1
    L[i] = A[p+i-1]
  for j = 1 to n2
    R[j] = A[q+j]
  L[n1+1] = ∞
  R{n1+1} = ∞
  i = 1
  j = 1
  for k = p to r
      if L[i] <= R[j]
        A[k] = L[i]
        i = i+1
      else
        A[k] = R[j]
        j = j+1


MERGE-SORT(A, p, r)
  if p   q = (p+r)/2
   MERGE-SORT(A, p, q)
   MERGE-SORT(A, q+1, r)
   MERGE(A, p, q, r)

C++代码:


#include
using namespace std;
/*
 * 归并排序
 * 使用递归方式
 * */
const int inf = 1e9+7;

void merge(int A[], int p, int q, int r){
    int n1 = q-p+1;
    int n2 = r-q;
    int L[n1+2];
    int R[n2+2];

    //初始化
    L[n1+1] = inf;
    R[n2+1] = inf;
    for (int i = 1; i <= n1; ++i)
        L[i] = A[p+i-1];
    for (int i = 1; i <= n2; ++i)
        R[i] = A[q+i];

    int i = 1;
    int j = 1;
    for (int k = p; k <= r; ++k) {
        if (L[i]<=R[j]){
            A[k] = L[i];
            i++;
        } else {
            A[k] = R[j];
            j++;
        }
    }
}

void mergeSort(int A[], int p, int r){
    if(p         int q = (p+r)/2;
        mergeSort(A, p, q);
        mergeSort(A, q+1, r);
        merge(A, p, q, r);
    }
}


int main(){
    int a[] = {0,2,4,5,6,7,9,8,1,10,3};
    int len = sizeof(a)/ sizeof(a[0]) -1;

    mergeSort(a,1,len);

    for (int i = 1; i <= len; ++i) {
        cout<     }
    cout<

    return 0;
}

 

你可能感兴趣的:(算法)