【hackerrank】Insertion Sort Advanced Analysis

Insertion Sort is a simple sorting technique which was covered in previous challenges. Sometimes, arrays may be too large for us to wait around for insertion sort to finish. Is there some other way we can calculate the number of times Insertion Sort shifts over elements 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

Sample Input:

2  
5  
1 1 1 2 2  
5  
2 1 3 1 2

Sample Output:

0  
4   

Recommended books for those interested in Data Structures and Algorithms

最后三个样例没过,哪位路过的兄台给指点一下?

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

void merge(unsigned int array[],unsigned int lhs, unsigned int mid, unsigned int rhs, int &res)
{
    unsigned int *tmp = new unsigned int[rhs-lhs+1];
    unsigned int i = lhs, j = mid + 1, k = 0;
    while(i <= mid && j <= rhs)
    {
        if(array[i] <= array[j])
        {
            tmp[k++] = array[i++];
        }
        else 
        {
            res += mid - i + 1;
            tmp[k++] = array[j++];
        }
    }
    while(i <= mid)
        tmp[k++] = array[i++];
    while(j <= rhs)
        tmp[k++] = array[j++];
    
    for(i = 0; i < k; i++)
        array[lhs+i] = tmp[i];
    delete[]tmp;
    
}

void mergesort( unsigned int array[], unsigned int lhs, unsigned int rhs, int &res)
{
    if(lhs < rhs)
    {
        unsigned int mid = lhs + (rhs - lhs)/2;
        mergesort(array,lhs,mid,res);
        mergesort(array,mid+1,rhs,res);
        merge(array,lhs,mid,rhs,res);
    }
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int T;
    cin>>T;
    while(T--)
    {
        int N;
        cin>>N;
        unsigned int *array = new unsigned int[N];
        for(int i = 0; i < N; i++)
            cin>>array[i];
        int res = 0;
        mergesort(array,0,N-1,res);
        cout<<res<<endl;
        delete[]array;
    }
    return 0;
}

思路是基于合并排序的思想。


你可能感兴趣的:(hackerrank)