0

I am trying to make my inversion counting program run faster since I am continuously getting TLE. I used C++ and this is my code

#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
    int n;
    int count = 0;
    cin >> n;
    int arr[n];
    for(int i = 0; i < n; i++)
    {
        cin >> arr[i];
    }
    for(int i = 0; i < n - 1; i++)
    {
        for(int j = i + 1; j < n; j++)
        if(arr[i] > arr[j])
        {
            count++;
        }
    }
    cout << count;
}

Help please!

mimi
  • 19
  • 6
  • 1
    search for something like "algorithm to count inversions" in your favorite engine for a better approach? – Marc Glisse Nov 02 '20 at 05:38
  • You should probably use the headerfile `#include` instead of `#include `. `#include ` is a C headerfile.. Or just drop it entirely. – Geno C Nov 02 '20 at 05:41
  • @GenoC or just drop that include since it is not used. – Marc Glisse Nov 02 '20 at 05:42
  • Your algo is slow because it is the trivial `O(n^2)` brute force approach. A merge sort like divide and conquer strategy exists that does this in `O(nlogn)` time. Search for it, it is easily available in the internet. – swag2198 Nov 02 '20 at 06:17
  • @swag2198 so it is a whole new algorithm I gotta teach my self? I am really confused here.. D: – mimi Nov 03 '20 at 04:43
  • If you know how `merge sort` works, it won't be totally new. Check [this](https://www.geeksforgeeks.org/counting-inversions/) out. – swag2198 Nov 03 '20 at 04:47
  • @swag2198 I got another problem here, I understood the merge sort that can divide it in O(nlogn) time but it seems to only work when there's an even number of numbers to count the inversion of. In my case, the amount of number is random so it seemed to not work for odd amount of numbers. – mimi Nov 22 '20 at 05:05
  • @mimi: No, it can work on odd no. of elements too. It just divides into 2 parts having `floor(n/2)` and `ceil(n/2)` elements ie, one part will have one more element than the other one and then it proceeds recursively. – swag2198 Nov 22 '20 at 09:01

0 Answers0