public class test_5{
public static void main(String[] args){
int[] arry = new int[]{9,8,7,6,5,4,3,2,1,0};
//System.out.println(sumArry_1(arry));
//System.out.println(sumArry_2(arry,0,9));
//System.out.println(sumArry_4(arry,0,9));
for(int i=0;i<arry.length;i++){
System.out.println(arry[i]+" ");
}
//System.out.println("---------------");
System.out.println(sumArry_3(arry,0,9));
for(int i=0;i<arry.length;i++){
System.out.println(arry[i]+" ");
}
}
public static int sumArry_1(int[] arry){
int k=0;
for(int i=0;i<arry.length;i++){
for(int j=i+1;j<arry.length;j++){
if(arry[i]>arry[j])
k++;
}
}
return k;
}
public static int sumArry_2(int[] arry,int low,int high){
if(low==high)
return 0;
int mid = (low + high )/2;
int leftSum=sumArry_2(arry,low,mid);
int rightSum=sumArry_2(arry,mid+1,high);
int mergeSum=mergeArry_1(arry,low,mid ,high);
return leftSum + rightSum + mergeSum ;
}
public static int mergeArry_1(int[] arry,int low,int mid ,int high){
int k=0;
for(int i=low;i<=mid;i++){
for(int j=mid+1;j<=high;j++){
if(arry[i]>arry[j])
k++;
}
}
return k;
}
public static int sumArry_3(int[] arry,int low,int high){
if(low==high)
return 0;
int mid = (low + high )/2;
int leftSum=sumArry_3(arry,low,mid);
int rightSum=sumArry_2(arry,mid+1,high);
int mergeSum=mergeArry_2(arry,low,mid ,high);
return leftSum + rightSum + mergeSum ;
}
public static int mergeArry_2(int[] arry,int low,int mid ,int high){
paiXu(arry,low,mid);
paiXu(arry,mid+1,high);
int sum=0;
for(int i=mid+1;i<=high;i++){
for(int k=low;k<=mid;k++){
if(arry[k]>arry[i]){
sum=sum+mid-low+1;
break;
}
}
}
return sum;
}
public static void paiXu(int[] arry,int low ,int high){
if(low==high)
return;
int mid=(low + high )/2;
paiXu(arry,low,mid);
paiXu(arry,mid+1,high);
mergeArry_3(arry,low ,mid,high);
}
public static void mergeArry_3(int[] arry,int low ,int mid,int high){
int k=low;
int j=mid+1;
int[] temp = new int [arry.length];
int w=0;
while(k<=mid && j<=high){
if(arry[k]>arry[j]){
temp[w]=arry[j];
w++;
j++;
}else{
temp[w]=arry[k];
w++;
k++;
}
}
if(k<=mid){
for(;k<=mid;w++,k++)
temp[w]=arry[k];
}
if(j<=high){
for(;j<=high;j++,w++)
temp[w]=arry[j];
}
w=0;
while(low<=high){
arry[low++]=temp[w++];
}
}
public static int sumArry_4(int[] arry,int low ,int high){
if(low == high)
return 0;
int mid =(low + high)/2;
int leftSum=sumArry_4(arry,low,mid);
int rightSum=sumArry_4(arry,mid +1,high);
int sum=mergeArry_4(arry,low,mid,high);
return leftSum + rightSum + sum;
}
public static int mergeArry_4(int[] arry,int low ,int mid,int high){
int k=low;
int j=mid+1;
int[] temp = new int [arry.length];
int w=0;
int sum=0;
while(k<=mid && j<=high){
if(arry[k]>arry[j]){
temp[w]=arry[j];
w++;
j++;
sum=sum+mid-low+1;
}else{
temp[w]=arry[k];
w++;
k++;
}
}
if(k<=mid){
for(;k<=mid;w++,k++)
temp[w]=arry[k];
}
if(j<=high){
for(;j<=high;j++,w++)
temp[w]=arry[j];
}
w=0;
while(low<=high){
arry[low++]=temp[w++];
}
return sum;
}
}