java歸併排序解逆序問題
阿新 • • 發佈:2019-01-06
public class test { public static void main(String[] args) { int[] array = {1,2,3,4,5,6,7,0}; test test = new test(); int i = test.InversePairs(array); for(int a:array){ System.out.println(a); } System.out.println(i); } public static int count = 0; // 設定一個全域性變數來記錄逆序的個數 public int InversePairs(int [] array) { if(array.length == 0){ return 0; } int [] temp = new int[array.length]; // 外部設定傳入陣列,可以減少空間複雜度 return Sort(array,0,array.length-1,temp); } private int Sort(int [] arry,int start, int end,int [] temp){ if(start >= end) return 0; int mid = (start+end)/2; Sort(arry,start,mid,temp); Sort(arry,mid+1,end,temp); return Merge(arry,start,mid,end,temp); } private int Merge(int [] array, int left,int mid, int right, int[] temp){ int temp1 = left; int temp2 = mid+1; int temp3 = 0; while (temp1 <= mid && temp2 <= right){ if(array[temp1] <= array[temp2]){ temp[temp3++] = array[temp1++]; }else { temp[temp3++] = array[temp2++]; count += temp2-temp1-1; // 這次交換改變的逆序個數 } } while (temp1<=mid){ temp[temp3++] = array[temp1++]; } while (temp2<=right){ temp[temp3++] = array[temp2++]; } int i = 0; // 把有序陣列存回原陣列 while (left<=right){ array[left++] = temp[i++]; } return count; } }