码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序(非原地版)

时间:2018-01-13 14:25:42      阅读:41      评论:0      收藏:0      [点我收藏+]

标签:include   gpo   using   sid   tar   post   std   end   delete   

#include <iostream>
using namespace std;


void merge(int* arr, int* reg, int start, int end) {
    if (start >= end)
        return;
    int left = start;
    int right = end;
    int mid = (left + right) / 2;
    merge(arr, reg, left, mid);
    merge(arr, reg, mid + 1, right);
    int start1 = left;
    int start2 = mid + 1;
    int resIdx = left;
    while (start1 <= mid && start2 <= right) {
        reg[resIdx++] = arr[start1] < arr[start2] ? arr[start1++] : arr[start2++];
    }
    while (start1 <= mid) {
        reg[resIdx++] = arr[start1++];
    }
    while (start2 <= right) {
        reg[resIdx++] = arr[start2++];
    }
    for (resIdx = start; resIdx <= end; resIdx++) {
        arr[resIdx] = reg[resIdx];
    }
}

void mergeSort(int* arr, int* reg, const int size) {
    merge(arr, reg, 0, size - 1);
}

int main() {
    int size, i;
    cin >> size;
    int *arr = new int[size];
    for (i = 0; i < size; i++) {
        cin >> arr[i];
    }
    int *reg = new int[size];
    mergeSort(arr, reg, size);
    cout << endl;
    cout << "Result:" << endl;
    for (i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    delete [] arr;
    delete [] reg;
    return 0;
}

归并排序(非原地版)

标签:include   gpo   using   sid   tar   post   std   end   delete   

原文地址:https://www.cnblogs.com/yanhewu/p/8278902.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!