數組中的逆序對:歸併排序的另類應用
數組中的逆序對:給定的數組,如果兩個數字中前面一個數字大於後面的一個,那麼稱為一個逆序對,數組中所有滿足此關係的逆序對總數就是這個數組的逆序對
此處的實現並不優雅,畢竟copy數組是不需要的,只需要一個局部的就可以
但是如果使用的是一個局部的空間複雜度是logn的輔助數組,會造成代碼有一點點難理解
另外,書上的明顯是錯誤的代碼,沒有運行過,但是從邏輯上來分析,應該會出現重複統計的問題
public class _Q36<T> { public int InversePairs(int nums[]){ if(nums == null) return 0; int copy[] = Arrays.copyOf(nums, nums.length); CommonUtils.PrintArray(copy); return InversePairsCore(nums, copy, 0, nums.length - 1); } private int InversePairsCore(int nums[], int copy[], int indexL, int indexR){ if(nums == null || indexL > indexR) return 0; if (indexL == indexR) { //copy[indexL] = nums[indexL]; return 0; } int len = (indexR - indexL) / 2; int leftCount = InversePairsCore(nums, copy, indexL, indexL + len); int rightCount = InversePairsCore(nums, copy, indexL + len + 1, indexR); int i = indexL + len; int j = indexR; int indexCopy = indexR; int count = 0; while(i >= indexL && j >= indexL + len + 1){ if(nums[i] > nums[j]){ // 出現逆序對 copy[indexCopy--] = nums[i--]; count = count + j - len - indexL; }else{ copy[indexCopy--] = nums[j--]; } } while(i >= indexL) copy[indexCopy--] = nums[i--]; while(j >= indexL + len + 1) copy[indexCopy--] = nums[j--]; for(int k=indexL; k<=indexR; k++){ nums[k] = copy[k]; } CommonUtils.PrintArray(copy); return leftCount + count + rightCount; } }
測試代碼:
public class _Q36Test extends TestCase { _Q36 inversePair = new _Q36(); public void test(){ int array[] = {7, 5, 6, 4}; System.out.println(inversePair.InversePairs(array)); } }