/**
* 使用归并排序的思想寻找逆序对(O(NlogN))
* @author Administrator
*
*/
public class Nixudui {
public static int InversePairs(int[] data,int length){
if(data==null||length==1)
return 0;
int[] copy = new int[length+3];
int count = InversePairsCore(data,copy,0,length-1);
return count;
}
public static int InversePairsCore(int[] data,int[] copy,int start,int end){
if(start==end){
copy[start] = data[start];
return 0;
}
int length = (end-start)/2;
int left = InversePairsCore(data,copy,start,start+length);
int right = InversePairsCore(data,copy,start+length+1,end);
int count = left+right;
int i = start+length;
int j = end;
int index = end;
while(i>=start&&j>=start+length+1){
if(data[i]>data[j]){
count+=i-start+1;
copy[index--] = data[i--];
}else{
copy[index--] = data[j--];
}
}
for(;i>=start;i--)
copy[index--] = data[i];
for(;j>=start+length+1;j--)
copy[index--] = data[j];
for(int k=index+1;k<=end;k++){
data[k] = copy[k];
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] data = {7,5,6,4};
System.out.println(InversePairs(data,4));
for(int i:data){
System.out.print(i+" ");
}
}
}
使用归并排序的思想寻找逆序对(O(NlogN))
猜你喜欢
转载自blog.csdn.net/qq_32635069/article/details/79800537
今日推荐
周排行