归并排序

Time Limit:7000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

Description

In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence
9 1 0 5 4 ,

Ultra-QuickSort produces the output
0 1 4 5 9 .

Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.

Input

The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.

Output

For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.

Sample Input

5
9
1
0
5
4
3
1
2
3
0

Sample Output

6
0

程序分析:此题的意思就是开始输入N代表接下来输入多少个数,然后在输入N一直循环,直到输入0为止。最后输出通过归并法要排几次序。这题的重点就是在于归并法的运用。代码中有两个条件是关键的。首先,只要有一个序列非空,就是继续合并,因此在比较时不能直接比较a[i],a[j],因为可能其中一个序列为空,从而可能会导致错误。

程序代码:

#include <iostream>
using namespace std;
#include<cstdio>
static unsigned  long long cnt = 0;
void merge(int* a, int* b, int beg, int mid, int end)
{
    int i = beg,k = 0,j = mid + 1;
    while (i <= mid && j <= end)
        if (a[i] <= a[j])
        {
            b[k] = a[i];
            ++i;
            ++k;
        }
        else
        {
            b[k] = a[j];
            ++j;
            ++k;
            cnt += mid + 1 - i;
        };

    while (i <= mid)
    {
        b[k] = a[i];
        ++i;
        ++k;
    }

    while (j <= end)
    {
        b[k] = a[j];
        ++j;
        ++k;
    }

    copy(&b[0],&b[k],&a[beg]);
};

void mergeSort(int* a, int* b, int beg, int end)
{
    if (beg < end)
    {
        int mid = (beg + end) >> 1;
        mergeSort(a, b, beg, mid);
        mergeSort(a, b, mid + 1, end);
        merge(a, b, beg, mid, end);
    }
};

int main()
{
    int N;
    int a[500001], b[500001];
    while (cin >> N && N != 0)
    {
        for (int i = 0; i < N; ++i) scanf("%d", &a[i]);
        cnt = 0;
        mergeSort(a,b,0,N - 1);

        cout << cnt <<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/yilihua/p/4702359.html