sorting - merge sort

Posted 小马识图

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sorting - merge sort相关的知识,希望对你有一定的参考价值。

#include "stdio.h"
#include "string.h"

#define MAX_LIST 50


typedef struct _SqList 
    int data[MAX_LIST];
    int length;
SqList;

enum MERGE_SORT_METHOD  RECURSE, ITERATE ;

void Merge( int src[], int dst[], int start, int middle, int end)

    int j, k;
    for( k = start, j = middle + 1; start <= middle && j <= end; k++   )
    
        if( src[start] < src[j] )
            dst[k] = src[start++];
        else
            dst[k] = src[j++];      
    

    while( start <= middle ) dst[k++] = src[start++];
    while( j <= end ) dst[k++] = src[j++];      


void MSort( int src[], int dst[], int start, int end )

    if( start == end )
        dst[start] = src[start];
    else
        int middle = (start + end)/2;
        int buf[MAX_LIST];
        MSort(src, buf, start, middle);
        MSort(src, buf, middle+1, end);
        Merge(buf, dst, start, middle, end );
    

void MergeSortRecursive( SqList* L )

     MSort( L->data, L->data, 0, L->length-1 );


void MergePiecewise( int src[], int dst[], int piece, int count )

    int i = 0;
    while( i < count - 2*piece + 1)
    
        Merge( src, dst, i, i+piece-1, i+2*piece-1);
        i += 2*piece;
       
    if( i < count -  piece + 1 )
        Merge( src, dst, i, i + piece - 1, count-1);
    else
        while( i < count )
            dst[i] = src[i++];

void MergeSortIterative( SqList* L )

    int buf[MAX_LIST];

    int block = 1;
    while( block < L->length )
    
        MergePiecewise( L->data, buf, block, L->length  );
        block *= 2;
        MergePiecewise( buf, L->data, block, L->length );
        block *= 2;
    


void MergeSort( SqList* L, MERGE_SORT_METHOD ms )

    if( ms == RECURSE )
        MergeSortRecursive( L );
    else
        MergeSortIterative( L );


int main()

    SqList d;
    int intarr[] = 1,10,23,48,65,31,-21,9,88,100;
    printf("array length is %d\\n", sizeof(intarr));
    memcpy( d.data, intarr, sizeof(intarr));
    d.length = sizeof(intarr)/sizeof(int);  
    int index = 0;
    for( ; index < d.length; index++ )
        printf(" %d", d.data[index] );
    printf("\\nMerge sort...\\n");
    MergeSort( &d, RECURSE );
    for( index = 0; index < d.length; index++ )
        printf(" %d", d.data[index] );
    printf("\\n");
    return 0;

以上是关于sorting - merge sort的主要内容,如果未能解决你的问题,请参考以下文章

排序算法--Merge Sorting--归并排序--Merge sort--归并排序

23. Merge k Sorted Lists

java [MergeSort] Merge Sort #LeetCode #Java #Recursion #Sort

java [MergeSort] Merge Sort #LeetCode #Java #Recursion #Sort

Merge Two Sorted Lists

21. Merge Two Sorted Lists