定义:对于数组A,如果存在下标 i < j 使得a[i] > a[j], 则称<a[i], a[j]>为一个逆序对。现对于一个给定的数组A,求其逆序对个数。
--------------------------------------------------------------------------------------------------
统计部分的算法伪代码大致如下:
i = start; j = mid + 1; num = 0; while(i <= med && j <= end) { if(A[i] >= A[j]){ j++; num+=mid - i + 1; }else{ i++; } }
----------------------------------------------------------------------
public class ReverseCouple { static int merge(int[]data, int start1, int start2, int end){ int low = start1; int lowBound = start2 - 1; int high = start2; int highBound = end; int[]tempData = new int[end - start1 + 1]; int count = 0;//累计逆序对 int tempIndex = 0; while(low <= lowBound && high <= highBound){ if(data[low] > data[high]){ tempData[tempIndex++] = data[high++]; count += lowBound - low + 1;//low~lowBound的数都大于high }else{ tempData[tempIndex++] = data[low++]; } } while(low <= lowBound){ tempData[tempIndex++] = data[low++]; } while(high <= highBound){ tempData[tempIndex++] = data[high++]; } for(int i = 0; i < tempData.length; i++){ data[i + start1] = tempData[i]; } return count; } static int mergeSort(int[]data, int low, int high){ if(low < high){ int mid = (low + high) / 2; int a = mergeSort(data, low, mid); int b = mergeSort(data, mid + 1, high); return a + b + merge(data, low, mid + 1, high); } return 0; } public static void main(String[]args){ int[]data = {2,-1,5,6,0,2,4,3}; printArray(data); System.out.println(); System.out.println(mergeSort(data, 0, data.length - 1)); printArray(data); } static void printArray(int[]data){ for(int value : data){ System.out.print(value + " , "); } } }