比熊科技 | APP开发 | APP制作

2019-03-28 01:28:06

//

//  mergeSort.h

//  bczm

//

//  Created by bichonfrise on 2019/3/27.

//  Copyright © 2019 bichonfrise. All rights reserved.

//


#ifndef mergeSort_h

#define mergeSort_h

#include

#include

#include


void merge(int* arr, int start, int end, int mid){

    int i = start;

    int j = mid;

    int k = 0;

    int* tmpArr = (int*)malloc(sizeof(int)*sizeof(end-start+1));

    while(i <= mid-1 && j<= end){

        if (arr[i] < arr[j]) {

            tmpArr[k++] = arr[i++];

        }

        else{

            tmpArr[k++] = arr[j++];

        }

    }

    

    while (i<mid) {

        tmpArr[k++] = arr[i++];

    }

    

    while (j<=end) {

        tmpArr[k++] = arr[j++];

    }

    for (int i = start,k=0; i<=end;) {

        arr[i++] = tmpArr[k++];

    }

}

void sortM(int* arr, int start, int end){

    int mid = (start + end)/2;

    if (start < end) {

        sortM(arr, start, mid);

        sortM(arr, mid+1, end);

        merge(arr,start,end,mid+1);

    }

}

void mergeSort(int* arr, int arrLen){

    int start = 0;

    int end = arrLen-1;

    sortM(arr, start, end);

    

}

void mergeSortMain(){

    int arr[] = {32,5,3,91,278,92,74,8,3,7,9};

    int arrLen = sizeof(arr)/sizeof(arr[0]);

    printArr(arr, arrLen);

    mergeSort(arr,arrLen);

    printArr(arr, arrLen);

}


#endif /* mergeSort_h */


BichonfriseSOFT

西安比熊网络科技有限公司

如您有疑问或需要帮助,
可以咨询一下商务经理

电话咨询17792315676