C - Ultra-QuickSort(7.2.2)(7.2应用排序算法编程的实验范例)

来源:互联网 发布:东莞网络外包 编辑:程序博客网 时间:2024/04/28 02:49

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

59105431230

Sample Output

6

0

#include <iostream>
#include <cstdio>
using namespace std;
const long long int maxn=510000;
long long int a[maxn],temp[maxn],n,cnt;
void sort1(long long int l,long long int r)
{
    if(l==r)
        return ;
    long long int mid=(l+r)/2;
    sort1(l,mid);
    sort1(mid+1,r);
    long long int i=l,j=mid+1,now=0;
    while(i<=mid&&j<=r)
    {
        if(a[i]>a[j])
        {
            cnt+=mid-i+1;
             temp[++now]=a[j++];
        }
        else
            temp[++now]=a[i++];
    }
    while(i<=mid)
        temp[++now]=a[i++];
    while(j<=r)
        temp[++now]=a[j++];
    now=0;
    for(long long int p=l;p<=r;p++)
        a[p]=temp[++now];

}
int main()
{
    //scanf("%lld",&n);
    cin>>n;
    while(n)
    {
        for(long long int k=1;k<=n;k++)
            cin>>a[k];
        cnt=0;
        sort1(1,n);
       // printf("%lld\n",cnt);
        //scanf("%lld",&n);
        cout<<cnt<<endl;
        cin>>n;
    }
    return 0;
}

 

 

 

0 0
原创粉丝点击