首页 > 代码库 > 【InversionCount 逆序对数 + MergeSort】
【InversionCount 逆序对数 + MergeSort】
Definition of Inversion: Let (A[0], A[1] ... A[n], n <= 50) be a sequence of n numbers. If i < j and A[i] > A[j], then the pair (i, j) is called inversion of A.
Example:Count(Inversion({3, 1, 2})) = Count({3, 1}, {3, 2}) = 2
思路,假设用brute force,则O(n^2),借用合并排序里面的合并步骤里的思路
import java.util.Arrays; public class MergeSort { static int InversionCount = 0; public static void main(String[] args) { int[] array = {3,1,2,5,4,7,6}; MergeSort(array, 0, array.length-1); System.out.println(InversionCount); System.out.println(Arrays.toString(array)); } public static void MergeSort(int[] array, int lhs, int rhs) { if (lhs < rhs) { int mid = lhs + ((rhs - lhs)>>1); MergeSort(array, lhs, mid); MergeSort(array, mid+1, rhs); Merge(array, lhs, mid, rhs); } } public static void Merge(int[] array, int lhs, int mid, int rhs) { int[] tmp = new int[rhs-lhs+1]; int i = lhs, j = mid+1; int k = 0; while(i <= mid && j <= rhs) { if (array[i] > array[j]) { InversionCount += mid-i+1; tmp[k++] = array[j++]; } else { tmp[k++] = array[i++]; } } while(i <= mid) { tmp[k++] = array[i++]; } while(j <= rhs) { tmp[k++] = array[j++]; } for (i = 0; i < k; i++) { array[i+lhs] = tmp[i]; } tmp = null; } }
【InversionCount 逆序对数 + MergeSort】
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。