SPOJ-CODESPTB Insertion Sort【插入排序】

Insertion Sort

  SPOJ - CODESPTB

Insertion Sort is a classical sorting technique. One variant of insertion sort works as follows when sorting an array a[1..N] in non-descending order:

for i <- 2 to N
    j <- i
    while j > 1 and a[j] < a[j - 1]
        swap a[j] and a[j - 1]
        j <- j - 1

The pseudocode is simple to follow. In the ith step, element a[i] is inserted in the sorted sequence a[1..i - 1]. This is done by moving a[i] backward by swapping it with the previous element until it ends up in it's right position.

As you probably already know, the algorithm can be really slow. To study this more, you want to find out the number of times the swap operation is performed when sorting an array.

Input

The first line contains the number of test cases T. T test cases follow. The first line for each case contains N, the number of elements to be sorted. The next line contains N integers a[1],a[2]...,a[N].

Output

Output T lines, containing the required answer for each test case.

Constraints

1 <= T <= 5
1 <= N <= 100000
1 <= a[i] <= 1000000

Example

Sample Input:
2
5
1 1 1 2 2
5
2 1 3 1 2

Sample Output:
0
4

问题链接SPOJ-CODESPTB Insertion Sort

问题简述:(略)

问题分析

  插入排序问题,求使用插入排序算法时数据交换的次数。

  没有想出来不排序怎么计算,就直接用排序算法实现了,中间统计一下交换的次数。

程序说明

  程序是插入排序的原始算法,稍微作了一些改动。

  插入排序算法封装到函数insertion_sort()中。


题记:(略)


参考链接:(略)


AC的C++语言程序如下:

/* SPOJ Insertion Sort */

#include <bits/stdc++.h>

using namespace std;

const int N = 100000;
int a[N];

int insertion_sort(int a[], int n)
{
    int cnt = 0;

    for(int i=1; i<n; i++) {
        int key = a[i];
        /* insert A[i] into the sorted sequence A[0,...,j-1] */
        int j = i - 1;
        while(j >= 0 && a[j] > key) {
            a[j + 1] = a[j];
            j--;
            cnt++;
        }
        a[j + 1] = key;
    }

    return cnt;
}

int main()
{
    int t, n;

    scanf("%d", &t);
    while(t--) {
        scanf("%d", &n);

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

        printf("%d\n", insertion_sort(a, n));
    }

    return 0;
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值