Summary: Merge Sort of Array && 求逆序对

时间:2021-12-31 23:45:20

常用算法(后面有inplace版本):

 package ArrayMergeSort;

 import java.util.Arrays;

 public class Solution {
public int[] mergeSort(int[] arr) {
if (arr.length == 1) return arr;
else {
int[] arr1 = Arrays.copyOfRange(arr, 0, arr.length/2);
int[] arr2 = Arrays.copyOfRange(arr, arr.length/2, arr.length);
return merge(mergeSort(arr1), mergeSort(arr2));
}
} public int[] merge(int[] arr1, int[] arr2) {
int len1 = arr1.length;
int len2 = arr2.length;
int[] res = new int[len1+len2];
int i = 0, j=0, cur=0;
while (i<len1 && j<len2) {
if (arr1[i] <= arr2[j]) {
res[cur++] = arr1[i++];
}
else {
res[cur++] = arr2[j++];
}
}
while (i<len1) {
res[cur++] = arr1[i++];
}
while (j<len2) {
res[cur++] = arr2[j++];
}
return res;
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution sol = new Solution();
int[] arr = sol.mergeSort(new int[]{6,5,4,8,2,1});
System.out.println(Arrays.toString(arr));
} }

在如上算法中只需稍作修改,加上一行代码,就可以求数组的逆序对

如数组 <2,3,8,6,1> 的逆序对为:<2,1> <3,1> <8,6> <8,1> <6,1> 共5个逆序对。

暴力法是O(N^2)

mergeSort可以O(NlogN)

定义一个static variable count, 然后在12行加入

 public int[] merge(int[] arr1, int[] arr2) {
int len1 = arr1.length;
int len2 = arr2.length;
int[] res = new int[len1+len2];
int i = 0, j=0, cur=0;
while (i<len1 && j<len2) {
if (arr1[i] <= arr2[j]) {
res[cur++] = arr1[i++];
}
else { // arr1[i] > arr2[j];
res[cur++] = arr2[j++];
count += arr1.length - i;
}
}
while (i<len1) {
res[cur++] = arr1[i++];
}
while (j<len2) {
res[cur++] = arr2[j++];
}
return res;
}

Inplace的mergeSort不是那么好写,我还是在merge的时候用了额外空间

 package ArrayMergeSort;

 import java.util.Arrays;

 public class Solution2 {

     public int[] mergeSort(int[] arr) {
if (arr==null || arr.length==0) return arr;
mergeSort(arr, 0, arr.length-1);
return arr;
} public void mergeSort(int[] arr, int l, int r) {
if (r-l == 0) return;
int m = (l+r)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, m+1, r);
} public void merge(int[] arr, int l1, int r1, int l2, int r2) {
int[] temp = new int[r2-l1+1];
int i1=l1, i2=l2, cur=0;
while (i1<=r1 && i2<=r2) {
if (arr[i1] <= arr[i2]) temp[cur]=arr[i1++];
else temp[cur] = arr[i2++];
cur++;
}
while(i1<=r1) temp[cur++]=arr[i1++];
while(i2<=r2) temp[cur++]=arr[i2++];
cur = 0;
for (int i=l1; i<=r2; i++) arr[i]=temp[cur++];
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution2 sol = new Solution2();
int[] arr = sol.mergeSort(new int[]{6,5,4,2,1});
System.out.println(Arrays.toString(arr));
} }

Iterative Merge Sort大致的算法是,假设每一层需要merge许多数组 A和B数组是其中两个,i 可以理解为A或B的size,从1一直到array.length/2. j 可以理解为一组A和B之中B的结束位置。 Merge函数跟上面一样

 Iterative Merge Sort
public static T[] Iterative(T[] array, IComparer<T> comparer)
{
for (int i = 1; i <= array.Length / 2 + 1; i *= 2)
{
for (int j = i; j < array.Length; j += 2 * i)
{
Merge(array, j - i, j, Math.Min(j + i, array.Length), comparer);
}
} return array;
}