Sorting Problem I NOJ1870 水 冒泡排序



Sorting Problem I

时间限制(普通/Java) : 1000 MS/ 2000 MS          运行内存限制 : 16384 KByte
总提交 : 688            测试通过 : 92 

题目描述

openxxx喜欢一切有序的事物,现在有一串数字,openxxx希望以最小的代价对这串数字从小到大进行排序(实现非递减序)。

openxxx只会交换任意两个相邻的数字,每做一次交换,就要消耗openxxx一格的体力值,当然openxxx希望消耗的体力值越少越好,你能计算出openxxx至少要消耗多少格体力值吗?



输入

多组测试数据,每组数据第一行包含一个正整数N(1<=N<=500)表示这串数字的个数,第二行包含N个正整数x1 x2 x3 …… xN(1<=xi<=N,1<=i<=N)用来描述这串原始数字序列,任意两个相邻数字之间用一个空格隔开。 


输出

每组测试数据对应一行输出,仅包含一个整数p,表示最少需要消耗的体力值数。


样例输入

2
1 2
3
3 1 2
2
1 1

样例输出

0
2
0


采用冒泡排序,定义一个变量统计每次交换的次数即可~水水~

实现代码:

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
int main()
{
    int n;
    while(scanf("%d",&n)==1)
    {
        int *pData=new int[n+1];
        for(int i=0;i<n;i++)
        {
            scanf("%d",&pData[i]);
        }
        int temp;
        int cnt=0;
        for (int i = 1; i<n; i++)
        {
            for (int j = n - 1; j >= i; j--)
            {
                if (pData[j] < pData[j - 1])
                {
                    temp = pData[j - 1];
                    pData[j - 1] = pData[j];
                    pData[j] = temp;
                    cnt++;
                }
            }
        }
        printf("%d\n",cnt);
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted on 2015-04-15 08:27  Tob__yuhong  阅读(114)  评论(0编辑  收藏  举报

导航