Skip to content

Instantly share code, notes, and snippets.

@yuvipanda
Created October 13, 2011 18:52
Show Gist options
  • Save yuvipanda/1285128 to your computer and use it in GitHub Desktop.
Save yuvipanda/1285128 to your computer and use it in GitHub Desktop.
Insertion Sort Solutions (InterviewStreet CodeSprint Fall 2011)

The answer is the number of inversions in the array, which is the number of pairs i,j such that i < j and a[i] > a[j]. Counting this is a fairly classical problem with many solutions such as using data structures such as Balanced Trees or Binary Indexed Trees. Another particularly elegant solution involves modifying merge sort to count the number of inversions when merging the two sorted halves in the algorithm.

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std ;
#define MAXN 100002
#define MAX 1000002
int n,a[MAXN],c[MAX] ;
int main()
{
int runs ;
scanf("%d",&runs) ;
while(runs--)
{
scanf("%d",&n) ;
for(int i = 0;i < n;i++) scanf("%d",&a[i]) ;
long long ret = 1LL * n * (n - 1) / 2 ;
memset(c,0,sizeof c) ;
for(int i = 0;i < n;i++)
{
for(int j = a[i];j > 0;j -= j & -j) ret -= c[j] ;
for(int j = a[i];j < MAX;j += j & -j) c[j]++ ;
}
cout << ret << endl ;
}
return 0 ;
}
@lvsl-deactivated
Copy link

What "j & -j" means in lines 20 and 21?

@ashi009
Copy link

ashi009 commented Mar 24, 2012

@lvsl: search "binary indexed tree"

@HariTejaVarma
Copy link

i did not understand 16 and 17 lines,please explain..............

@gyan0007
Copy link

gyan0007 commented Sep 3, 2012

I just don't understand how "int n,a[MAXN],c[MAX]" will make the prog. work. In compilers where integer is 2 byte, this will fail. Please use long instead.

@mukulgarg
Copy link

plz anyone tell me more abot the statement

j-=j&-j
Thanks in advance

@iprebeg
Copy link

iprebeg commented Dec 1, 2012

@nma
Copy link

nma commented Dec 16, 2012

Python version on pythontutor.com, the code visualization might help.

http://goo.gl/uKh8Z

@debidatta
Copy link

@nma Line 8 should be

for x in range(MAX):

in the code on pythontutor you linked to. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment