# 算法导论学习1--分治法计算逆序数

闲来无事，复习复习经典的算法导论。看到了2-4，习题，计算逆序数的问题，忍不住实现了一下。

public class MergInversionCount {
public static int count(int[] array, int p, int r) {
int inversionCount = 0;
if (p < r) {
int mid = (p + r) / 2;
inversionCount += count(array, p, mid);
inversionCount += count(array, mid+1, r);
inversionCount += mergeInversion(array, p, mid, r);
}
return inversionCount;
}

private static int mergeInversion(int[] array, int p, int mid, int r) {
int inversionCount = 0;
int[] temp = new int[r-p+1];
if(array.length < r)
return inversionCount;
int left = p;
int right = mid + 1;
int storeIndex = 0;
while(left <= mid && right <= r)
{
if(array[left] > array[right])
{
inversionCount += mid-left+1; //当前right存在逆序数，数目等于mid-left+1
temp[storeIndex] = array[right];
right++;
}
else
{
temp[storeIndex] = array[left];
left++;
}
storeIndex++;
}
if(left <= mid)
{
for(int i = left; i <= mid; i++)
{
temp[storeIndex] = array[i];
storeIndex++;
}
}
if(right <= r)
{
for(int i = right; i <= r; i++)
{
temp[storeIndex] = array[i];
storeIndex++;
}
}

for(int i = p; i <= r; i++)
{
array[i] = temp[i-p];

}
return inversionCount;
}

}

import static org.junit.Assert.*;

import org.junit.Test;

public class MergInversionCountTest {

@Test
public void testCount() {
int[] array = {1,5,6,7,4};
int[] array2 = {1,5,6,7,4,3,11, 15, 13, 2, 8};

int inversionCount = MergInversionCount.count(array, 0, 4);
assertTrue(inversionCount == 3 );

inversionCount = MergInversionCount.count(array2, 4, 10);
assertTrue(inversionCount == 10 );

}

}

#### 逆序数的几种求法

2012-05-23 15:38:43

#### 逆序数的分治算法

2016-05-15 22:16:37

#### 求逆序数

2011-09-19 18:52:19

#### 逆序数算法

2008-04-21 09:30:00

#### 排列逆序数和计算

2014-12-13 18:01:20

#### 求逆序数对个数（微软2010年笔试题）

2014-04-22 22:40:55

#### 使用分治法计算逆序数——算法

2014-10-25 22:06:57

#### 逆序数（分治）

2017-06-11 00:08:18

#### NOI2.4基本算法之分治 求排列的逆序数 分析----也是醉了...

2016-08-18 11:18:35

#### 归并排序-求逆序数算法

2013-08-01 00:56:15