Count inversion algorithm