Merge sort and its ramifications
The method of merging two sorted array portions merge into one. A large array into two smaller arrays to solve it. Problem because each half will be divided into two sub-problems, the complexity of this algorithm is generally bisecting O (NlogN).
public class Sort{
public static void mergeSort(int []arr){
if(arr==null||arr.length<2)
return ;
mergeSort(arr,0,arr.length-1);
}
public static void mergeSort(int[]arr,int left,int right){
if(left==right)
return;
int mid=left+(right-left)/2;
mergeSort(arr,left,mid);
mergeSort(arr,mid+1,right);
merge(arr,left,mid,right);//合并
}
public static void merge(int []arr,int left,int mid,int right){
int []temp=new int[right-left+1]; //辅助数组
int k=0;
int i=left;
int j=mid+1;
while(i<=mid&&j<=right){
if(arr[i]<arr[j]){
temp[k++]=arr[i++];
}else{
temp[k++]=arr[j++];
}
}
while(i<=mid){
temp[k++]=arr[i++];
}
while(j<=right){
temp[k++]=arr[j++];
}
for(k=0;k<temp.length;k++){
arr[left+k]=temp[k];
}
}
}
Derived based on merge sort Title: Small and problems and to reverse the problem.
Small and question refers to a given array, each element of the array on the left is less than the sum of its elements is. 1.3.2.6.5 array example, it is small and 1 + 1 + 1 + 2 + 3 + 3 + 2 + 1 = 14.
code show as below:
public class Sort{
public static int smallSum(int []arr){
if(arr==null||arr.length<2)
return 0;
return mergeSort(arr,0,arr.length-1);
}
public static int mergeSort(int []arr,int l,int r){
if(l==r)
return 0;
int mid=l+((r-l)>>1);
return mergeSort(arr,l,mid)+mergeSort(arr,mid+1,r)+merge(arr,l,mid,r);
}
public static int merge(int arr,int l,int mid ,int r){
int []temp=new int[r-l+1];
int k=0;
int res=0;
int i=l;
int j=mid+1;
while(i<=mid&&j<=r){
res+=arr[i]<arr[j]?(r-j+1)*arr[i]:0;//计算小和
temp[k++]=arr[i]<arr[j]?arr[i++]:arr[j++];
}
while(i<=m){
temp[k++]=arr[i++];
}
while(j<=r){
temp[k++]=arr[j++];
}
for(k=0;k<temp.length;k++){
arr[l+k]=temp[k];
}
return res;
}
}