归并排序

##(1)先上PPT
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
##(2)伪代码

/* 归并排序 - 递归实现 */
 
/* L = 左边起始位置, R = 右边起始位置, RightEnd = 右边终点位置*/
void Merge( ElementType A[], ElementType TmpA[], int L, int R, int RightEnd )
{ /* 将有序的A[L]~A[R-1]和A[R]~A[RightEnd]归并成一个有序序列 */
     int LeftEnd, NumElements, Tmp;
     int i;
      
     LeftEnd = R - 1; /* 左边终点位置 */
     Tmp = L;         /* 有序序列的起始位置 */
     NumElements = RightEnd - L + 1;
      
     while( L <= LeftEnd && R <= RightEnd ) {
         if ( A[L] <= A[R] )
             TmpA[Tmp++] = A[L++]; /* 将左边元素复制到TmpA */
         else
             TmpA[Tmp++] = A[R++]; /* 将右边元素复制到TmpA */
     }
 
     while( L <= LeftEnd )
         TmpA[Tmp++] = A[L++]; /* 直接复制左边剩下的 */
     while( R <= RightEnd )
         TmpA[Tmp++] = A[R++]; /* 直接复制右边剩下的 */
          
     for( i = 0; i < NumElements; i++, RightEnd -- )
         A[RightEnd] = TmpA[RightEnd]; /* 将有序的TmpA[]复制回A[] */
}
 
void Msort( ElementType A[], ElementType TmpA[], int L, int RightEnd )
{ /* 核心递归排序函数 */ 
     int Center;
      
     if ( L < RightEnd ) {
          Center = (L+RightEnd) / 2;
          Msort( A, TmpA, L, Center );              /* 递归解决左边 */ 
          Msort( A, TmpA, Center+1, RightEnd );     /* 递归解决右边 */  
          Merge( A, TmpA, L, Center+1, RightEnd );  /* 合并两段有序序列 */ 
     }
}
 
void MergeSort( ElementType A[], int N )
{ /* 归并排序 */
     ElementType *TmpA;
     TmpA = (ElementType *)malloc(N*sizeof(ElementType));
      
     if ( TmpA != NULL ) {
          Msort( A, TmpA, 0, N-1 );
          free( TmpA );
     }
     else printf( "空间不足" );
}
/* 归并排序 - 循环实现 */
/* 这里Merge函数在递归版本中给出 */
 
/* length = 当前有序子列的长度*/
void Merge_pass( ElementType A[], ElementType TmpA[], int N, int length )
{ /* 两两归并相邻有序子列 */
     int i, j;
       
     for ( i=0; i <= N-2*length; i += 2*length )
         Merge( A, TmpA, i, i+length, i+2*length-1 );
     if ( i+length < N ) /* 归并最后2个子列*/
         Merge( A, TmpA, i, i+length, N-1);
     else /* 最后只剩1个子列*/
         for ( j = i; j < N; j++ ) TmpA[j] = A[j];
}
 
void Merge_Sort( ElementType A[], int N )
{ 
     int length; 
     ElementType *TmpA;
      
     length = 1; /* 初始化子序列长度*/
     TmpA = malloc( N * sizeof( ElementType ) );
     if ( TmpA != NULL ) {
          while( length < N ) {
              Merge_pass( A, TmpA, N, length );
              length *= 2;
              Merge_pass( TmpA, A, N, length );
              length *= 2;
          }
          free( TmpA );
     }
     else printf( "空间不足" );
}

##(3)测试代码

//分而治之----递归算法
##include<cstdio>
using namespace std;
##define MAXN 110

int N;
int Init[MAXN];
int Num[MAXN];

void Merge(int l, int r, int rightEnd){
    int leftEnd, numElements, temp;
    int i;

    leftEnd = r - 1;
    temp = l;
    numElements = rightEnd - l + 1;

    while(l <= leftEnd && r <= rightEnd){
        if(Init[l] <= Init[r])
            Num[temp++] = Init[l++];
        else
            Num[temp++] = Init[r++];
    }

    while( l <= leftEnd)
        Num[temp++] = Init[l++];
    while( r <= rightEnd)
        Num[temp++] = Init[r++];

    for(i = 0 ; i < numElements; ++i, rightEnd--)
        Init[rightEnd] = Num[rightEnd];
}

void MSort(int l, int rightEnd){
    int center;
    if(l < rightEnd){
        center = (l + rightEnd) / 2;
        MSort(l, center);
        MSort(center + 1, rightEnd);
        Merge(l, center + 1, rightEnd);
    }
}

int main(void){
    scanf("%d", &N);
    for(int i = 0 ; i < N; ++i){
        scanf("%d", &Init[i]);
    }
    MSort(0, N - 1);
    for(int i = 0; i < N; ++i){
        printf("%d ", Init[i]);
    }

    return 0;
}
public class MergeSort {

    // Time: O(n * log(n)), Space: O(n)
    public void sortRecursive(int [] arr) {
        if (arr == null || arr.length == 0) return;

        int [] tmp = new int[arr.length];

        mergeSort(arr, 0, arr.length - 1, tmp);
    }

    private void mergeSort(int[] arr, int low, int high, int[] tmp) {
        if (low < high) {
            int mid = low + (high - low) / 2;
            mergeSort(arr, low, mid, tmp);
            mergeSort(arr, mid + 1, high, tmp);
            merge(arr, low, mid, high, tmp);
        }
    }

    private void merge(int[] arr, int low, int mid, int high, int[] tmp) {
        int i = low, j = mid + 1, k = 0;
        while (i <= mid && j <= high) {
            if (arr[i] <= arr[j]) tmp[k++] = arr[i++];
            else tmp[k++] = arr[j++];
        }
        while (i <= mid) tmp[k++] = arr[i++];
        while (j <= high) tmp[k++] = arr[j++];
        System.arraycopy(tmp, 0, arr, low, k);
    }

    // Time: O(n * log(n)), Space: O(n)
    public void sortIterative(int [] arr) {

        if (arr == null || arr.length == 0) return;

        int n = arr.length;

        int [] tmp = new int[n];

        for (int len = 1; len < n; len = 2 * len) {
            for (int low = 0; low < n; low += 2 * len) {
                int mid = Math.min(low + len - 1, n - 1);
                int high = Math.min(low + 2 * len - 1, n - 1);
                merge(arr, low, mid, high, tmp);
            }
        }
    }
}

####习题:https://pta.patest.cn/pta/test/16/exam/4/question/675
5-13 Insert or Merge (25分)
According to Wikipedia:

Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. Each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.

Merge sort works as follows: Divide the unsorted list into N sublists, each containing 1 element (a list of 1 element is considered sorted). Then repeatedly merge two adjacent sublists to produce new sorted sublists until there is only 1 sublist remaining.

Now given the initial sequence of integers, together with a sequence which is a result of several iterations of some sorting method, can you tell which sorting method we are using?

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer NN (\le 100≤100). Then in the next line, NN integers are given as the initial sequence. The last line contains the partially sorted sequence of the NN numbers. It is assumed that the target sequence is always ascending. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in the first line either “Insertion Sort” or “Merge Sort” to indicate the method used to obtain the partial result. Then run this method for one more iteration and output in the second line the resuling sequence. It is guaranteed that the answer is unique for each test case. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

Sample Input 1:

10
3 1 2 8 7 5 9 4 6 0
1 2 3 7 8 5 9 4 6 0
Sample Output 1:

Insertion Sort
1 2 3 5 7 8 9 4 6 0
Sample Input 2:

10
3 1 2 8 7 5 9 4 0 6
1 3 2 8 5 7 4 9 0 6
Sample Output 2:

Merge Sort
1 2 3 8 4 5 7 9 0 6

####思路:

就是插入排序前面为有序,后面为无序,以此来判断
##include<iostream>
##include<algorithm>
##include<cstdio>
using namespace std;
##define MAXN 110

int N;
int Init[MAXN];
int Num[MAXN];

void solve();
bool whichSort();
void nextStep_MergeSort(int len);
int getMergeLength();


int main(void){
    scanf("%d", &N);
    for(int i = 0 ; i < N; ++i){
        scanf("%d", &Init[i]);
    }
    for(int i = 0 ; i < N; ++i){
        scanf("%d", &Num[i]);
    }
    solve();
    return 0;
}

void solve(){
    if(whichSort()){
        printf("Merge Sort\n");
        nextStep_MergeSort(getMergeLength());
    }else{
        printf("Insertion Sort\n");
    }
    for(int i = 0; i < N; ++i){
        if(!i) printf("%d", Num[i]);
        else printf(" %d", Num[i]);
    }
}

bool whichSort(){
    int len = 1;    //记录插入排序中,有序子列的个数
    for(int i = 0; i < N - 1; ++i){
        if(Num[i] > Num[i + 1]){
            len = i + 1;
            break;
        }
    }

    for(int i = len; i < N; ++i)
        if(Num[i] != Init[i]) return true;  //MergeSort

    sort(Num, Num + len + 1);
    return false;
}

int getMergeLength(){
    for(int len = 2; len <= N / 2; len *= 2){
        int i;
        for(i = 0; i <= N - 2*len; i += 2 * len)
            if(!is_sorted(Num + i, Num + i + 2 * len)) return len;
        if(!is_sorted(Num + i, Num + N)) return len;
    }
    return N;   //全有序,输入有误
}

void nextStep_MergeSort(int len){

    int i = 0;
    for(; i < N - 2 * len; i += 2 * len)
        sort(Num + i, Num + i + 2 * len);
    sort(Num + i, Num + N);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值