hdu 2689 Sort it

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2689

题目分析:求至少交换多少次可排好序,可转换为逆序对问题。 用冒泡排序较为简单,复杂度较大~~ 也可用归并排序,复杂度O(lognn), 统计个数后复杂都不变。

/*

Sort it



Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 2660    Accepted Submission(s): 1910





Problem Description

You want to processe a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. Then how many times it need.

For example, 1 2 3 5 4, we only need one operation : swap 5 and 4.

 



Input

The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 1000); the next line contains a permutation of the n integers from 1 to n.

 



Output

For each case, output the minimum times need to sort it in ascending order on a single line.

 



Sample Input

3

1 2 3

4 

4 3 2 1 

 



Sample Output

0

6

 



Author

WhereIsHeroFrom

 



Source

ZJFC 2009-3 Programming Contest

 

*/

//冒泡排序

#include <cstdio>

const int maxn = 1000 + 10;

int a[maxn];

void swap(int i, int j)

{

    int t;

    t = a[i];

    a[i] = a[j];

    a[j] = t;

}



int main()

{

    int n;

    while(~scanf("%d", &n)){

        int cnt = 0;

        for(int i = 0; i < n; i++) scanf("%d", &a[i]);

        for(int i = 0; i < n-1; i++)

            for(int j = n-1; j >= i+1; j--){

                if(a[j] < a[j-1]){

                     swap(j, j-1);

                     cnt++;

                }

            }

        printf("%d\n", cnt);

    }

    return 0;

}



//归并排序

#include <cstdio>

#include <cstring>

const int maxn = 1000 + 10;

int a[maxn], t[maxn], cnt;

void merge_sort(int x, int y)

{

    if(y-x > 1){

    int m = x + (y-x)/2;

    int p = x, q = m, i = x;

    merge_sort(x, m);

    merge_sort(m, y);

    while(p < m || q < y){

        if(q >= y || (p < m && a[p] <= a[q])) t[i++] = a[p++];

        else {

            t[i++] = a[q++];

            cnt += m-p;

        }

    }

    for(i = x; i < y; i++) a[i] = t[i];

    }

}



int main()

{

    int n;

    while(~scanf("%d", &n)){

        for(int i = 0; i < n; i++){

            scanf("%d", &a[i]);

        }

        cnt = 0;

        merge_sort(0, n);

        printf("%d\n", cnt);

    }

    return 0;

}

 

你可能感兴趣的:(sort)