<>里面的一道题.今天上午看的东西.
逆序对,举个例子,A[0] > A[1],则A[0]和A[1]是一对逆序对.呵呵.按照书上所说,用归并排序实现.我给实现了.
思路很清晰,很享受研究算法的过程.
/*2-4-11-04-06-13.16.c -- 第二章第四题*/
#include
#include
#define SIZE (27)
int main (void) ;
int mergeSort (int * const array, const int left, const int right) ;
int merge (int * const array, const int left, const int middle, const int right) ;
void printResult (const int * const array, const int size) ;
int main (void)
{
int array[SIZE] = {4, 2, 9, 7, 6, 3, 1, 5, 7, 54, 12, 87, 14, 62, 15, 0, 54, 33, 41, 87, 56, 43, 76, 53, 21, 46, 88} ;
int size = SIZE ;
printf ("%d/n", mergeSort (array, 0, size - 1)) ;
printResult (array, size) ;
return 0 ;
}
int mergeSort (int * const array, const int left, const int right)
{
static int count = 0 ;
int middle ;
if (left < right)
{
middle = (left + right) / 2 ;
mergeSort (array, left, middle) ;
mergeSort (array, middle + 1, right) ;
count += merge (array, left, middle, right) ;
return count ;
}
else
return 0 ;
}
int merge (int * const array, const int left, const int middle, const int right)
{
int * first, * second ;
int fLenth, sLenth ;
int i, j, k ;
int count ;
fLenth = middle - left + 1 ;
sLenth = right - middle ;
first = (int *) malloc (sizeof (int) * fLenth) ;
second = (int *) malloc (sizeof (int) * sLenth) ;
for (i = 0; i < fLenth; i++)
first[i] = array[left + i] ;
for (j = 0; j < sLenth; j++)
second[j] = array[middle + j + 1] ;
count = 0 ;
i = j = 0 ;
for (k = left; k <= right; k++)
{
if (first[i] <= second[j])
array[k] = first[i++] ;
else
{
array[k] = second[j++] ;
count += fLenth - i ;
}
if (i == fLenth)
{
k++ ;
while (k <= right)
array[k++] = second[j++] ;
break ;
}
else if (j == sLenth)
{
k++ ;
while (k <= right)
array[k++] = first[i++] ;
break ;
}
}
free (first) ;
free (second) ;
return count ;
}
void printResult (const int * const array, const int size)
{
int i ;
for (i = 0; i < size; i++)
printf ("%-3d", array[i]) ;
putchar ('/n') ;
}