The reverse order of a sequence is two elements, for sequence A, I>j and A[i]<a[j], so a[i] and a[j] form a reverse pair.
It is meaningful to study the number of reverse pairs in a sequence, and for the insertion sort, the time of the order is proportional to the order of the ordered sequence.
The following is an algorithm for finding the number of reverse pairs in a sequence, similar to the divide-and-conquer algorithm used in merge sorting: The number of reverse pairs for the number of the left half of the sequence, plus the number of reverse pairs of the right half part, Finally, the left half of the element is larger than the right half of the element when merging. This is almost exactly the same as merging the algorithm, only adding the counting operation when merging, the complete algorithm is:
#include <stdio.h>
void display (int array[], int size)
{
int i;
for (i = 0; i < size; ++i)
{
printf ("%d", array[i]);
}
printf ("\ n");
}
int merge_inversion (int array[], int low, int middle, int high)
{
int count = 0;
int Llen = Middle-low + 1;
int hlen = High-middle;
int *l = (int *) malloc ((Llen + 1) * sizeof (int));
int *h = (int *) malloc ((Hlen + 1) * sizeof (int));
int I, j, K;
for (i = 0; i < Llen; i++)
L[i] = Array[low + i];
L[i] = 99999;
for (i = 0; i < Hlen; i++)
H[i] = array[middle + i + 1];
H[i] = 99999;
for (i = 0, j = 0, k = low; K < high + 1; k++)
{
if (L[i] > H[j])
{
ARRAY[K] = h[j++];
Count + = Llen-i;
}
Else
{
ARRAY[K] = l[i++];
}
}
Free (L);
Free (H);
return count;
}
int count_inversion (int array[], int low, int high)
{
int count = 0, middle;
if (Low < high)
{
Middle = low + (high-low)/2;
Count + = count_inversion (array, low, middle);
Count + = count_inversion (array, middle + 1, high);
Count + = merge_inversion (array, low, middle, high);
}
return count;
}
int main ()
{
int array[]={2,8,3,6,1};
printf ("Count of inversions is%d\n", count_inversion (array, 0, 4));
Display (array, 5);
return 0;
}