pat甲级1089

以趟为单位分割排序过程,每进行一趟排序后就和结果对比一次。
涉及到插入排序,归并排序非递归的写法:

#include 
#include 

bool isSame(int a[], int b[], int n);
void printArray(int a[], int n);
//一趟插入排序
void insertionSort(int a[], int i);
//一趟归并排序, group_size从1开始倍增到n
void merge_within_array(int a[], int L1, int R1, int L2, int R2);
void mergeSort(int a[], int n, int group_size);

int main(){
    int N;
    scanf("%d", &N);
    int init_seq[N], backup_seq[N], res_seq[N];
    for(int i=0; i<N; i++){
        scanf("%d", &init_seq[i]);
        backup_seq[i] = init_seq[i];
    }
    for(int i=0; i<N; i++) scanf("%d", &res_seq[i]);

    //每做一趟插入排序,就和结果对比一次
    for(int i=1; i<N; i++){
        insertionSort(init_seq, i);
        if(isSame(init_seq, res_seq, N)){
            printf("Insertion Sort\n");
            insertionSort(init_seq, i+1);
            printArray(init_seq, N);
            return 0;
        }
    }

    //运行到此处排除了插入排序的可能,尝试归并排序
    for(int i=1; i<=N; i*=2){
        mergeSort(backup_seq, N, i);
        if(isSame(backup_seq, res_seq, N)){
            printf("Merge Sort\n");
            mergeSort(backup_seq, N, 2*i);
            printArray(backup_seq, N);
            return 0;
        }
    }
}

bool isSame(int a[], int b[], int n){
    for(int i=0; i<n; i++){
        if(a[i]!=b[i]) return false;
    }
    return true;
}

void printArray(int a[], int n){
    for(int i=0; i<n; i++){
        printf("%d", a[i]);
        if(i<n-1) printf(" ");
    }
}

void insertionSort(int a[], int i){
    int temp = a[i];
    //利用upper_bound()函数实现二分查找的插入排序
    int first_greater = std::upper_bound(a, a+i, a[i]) - a;
    for(int j=i-1; j>=first_greater; j--) a[j+1] = a[j];
    a[first_greater] = temp;
}

void merge_within_array(int a[], int L1, int R1, int L2, int R2){
    int p=L1, q=L2, t=0;
    int temp[R2-L1+1];
    while(p<=R1 && q<=R2){
        if(a[p]<a[q]) temp[t++] = a[p++];
        else temp[t++] = a[q++];
    }
    while(p<=R1) temp[t++] = a[p++];
    while(q<=R2) temp[t++] = a[q++];
    for(int i=0; i<t; i++) a[L1+i] = temp[i];
}

void mergeSort(int a[], int n, int group_size){
    for(int i=0; i<n; i+=2*group_size){
        if(i+group_size<n){
            merge_within_array(a, i, i+group_size-1, i+group_size, std::min(i+2*group_size-1, n-1));
        }
    }
}

你可能感兴趣的:(pat甲级1089)