目前整理求数组逆序对个数的两种方式:
一是利用归并排序的特点,在合并两段数组的时候可以得到当前合并串的逆序对个数,归并完毕后即可得到所有逆序对个数;
二是利用树状数组,原始数组中的值对应到树状数组中的下标,每次更新就是当前点及其所有父节点+1。根据树状数组特点可以快速算出比当前点小的节点个数,然后用当前所有节点个数减去上值就是所有比它大的个数,也即是当前点的逆序对个数,对所有数都用上述方式求解逆序对个数依次累加可得到最后结果。
归并排序解法:
package blog.xu;
public class ReversePair {
private static int ReversePairNum = 0;
public static void partition(int[] array,int offset,int end){
if(offset < end){
int mid = (offset+end)/2;
partition(array,offset,mid);
partition(array,mid+1,end);
merge(array,offset,mid,end);
}
}
public static void merge(int[] array,int offset,int mid,int end){
int[] temp = new int[end-offset+1];
int n = offset , m = mid+1 ,cur = 0;
while(n <= mid && m <= end){
if(array[n] <= array[m]){
temp[cur++] = array[n++];
}
else{
temp[cur++] = array[m++];
ReversePairNum += mid-n+1;
}
}
while( n <= mid) temp[cur++] = array[n++];
while( m <= end) temp[cur++] = array[m++];
for(int i = 0 ; i < temp.length ; ++i){
array[offset + i] = temp[i];
}
}
public static int getReversePairNum(int[] array){
partition(array,0,array.length-1);
return ReversePairNum;
}
public static void main(String[] args) {
int[] array = new int[]{1,5,3,8,12,45,8,36,25,100,49,22,45,66,2,45,91,25,18};
System.out.println(getReversePairNum(array));
}
}
树状数组解法:
package blog.xu;
public class ReversePair {
private static int ReversePairNum = 0;
public static int lowbit(int num){
return num&(-num);
}
public static void update(int[] c,int index){
while(index < c.length){
c[index] += 1;
index += lowbit(index);
}
}
public static int sum(int[] c,int index){
int sum = 0;
while(index > 0){
sum += c[index];
index -= lowbit(index);
}
return sum;
}
public static int getReversePairNum(int[] array,int max){
int[] c = new int[max+1];
for(int i = 0 ; i < array.length ; ++i){
update(c,array[i]);
ReversePairNum += i+1 - sum(c,array[i]);
}
return ReversePairNum;
}
public static void main(String[] args) {
int[] array = new int[]{1,5,3,8,12,45,8,36,25,100,49,22,45,66,2,45,91,25,18};
System.out.println(getReversePairNum(array,100));
}
}