归并排序代码

#include <iostream>
#include <math.h>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

int Merge_(int low, int mid, int high, int *A)
{
    int i, j, h, k;
    h = low;
    i = low;
    j = mid + 1;
    int B[high - low + 1];
    while(h <= mid && j <= high)
    {
        if(A[h] <= A[j])
        {
            B[i-low] = A[h];
            h++;
        }
        else
        {
            B[i-low] = A[j];
            j++;
        }
        i++;
    }
    if(h > mid)
    {
        for(k = j; k <= high; k++)
        {
            B[i-low] = A[k];
            i++;
        }
    }
    else
    {
        for(k = h; k <= mid; k++)
        {
            B[i-low] = A[k];
            i++;
        }
    }
    for(k = low; k <= high; k++)
    {
        A[k] = B[k-low];
    }
    return 0;
}

int MergeSortL(int low, int high, int* A)
{
    int mid;
    if(low < high)
    {
        mid = floor((low + high)/2);
        MergeSortL(low, mid, A);
        MergeSortL(mid + 1, high, A);
        Merge_(low, mid, high, A);
    }
    return 0;
}

int main()
{
    clock_t start, finish;
    double duration;
    start = clock();

    ifstream in("array8.txt");
    ofstream out("result8.txt");
    int count_;
    in >> count_;
    int A[count_];
    for(int i = 0; i < count_; i++)
    {
        in >> A[i];
    }
    MergeSortL(0, count_ - 1, A);
    finish = clock();
    duration = (double)(finish - start)/CLOCKS_PER_SEC;
    cout << "ºÄʱ£º" << duration << "*****";
    out << "ºÄʱ£º" << duration << "*****";
    for(int i = 0; i < count_ - 1; i++)
    {
        out << A[i] << ",";
    }
    out << A[count_ - 1];
    cout << "The project is finished!" << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值