题目原文:

An inversion in an array a[] is a pair of entries a[i] and a[j] such that i<j but a[i]>a[j]. Given an array, design a linearithmic algorithm to count the number of inversions.

分析:

如果没有性能限制,用插入排序算法可以实现。题目性能被限制在nlogn,又是归并排序的练习题,很显然要实现个归并排序,并在里面计数。通过一个例子来看下计数方法,例如{6, 5, 2, 3, 4, 1}这个序列,归并过程中会分为分为如下几步:

1. 归并{6, 5},存在一次右侧元素5移至左侧的操作,变成{5, 6},归并前逆序对<6,5>

2. 归并{5, 6, 2},存在一次右侧元素2移至左侧的操作, 变成{2, 5, 6},归并前存在两对逆序对<5, 2>和<6, 2>

3. 归并{3, 4},不存在右侧元素左移操作

4. 归并{3, 4, 1},存在一次右侧元素1移至左侧的操作,变成{1, 3, 4},归并前存在两对逆序对<3, 1>和<4, 1>

5. 归并{2, 5, 6, 1, 3, 4},存在三次1、3、4右侧元素移至左侧的操作,归并前存在七对逆序对<2,1><5,1><6,1><5,3><6,3><5,4><6,4>

由上述分析可见,当右侧元素a[j]与左侧元素a[i]进行比较后需要移至左侧时,a[j]与区间 [ a[i] , a[mid] ]中的所有元素都可以组成逆序对,这个区间的元素个数为mid+1-i个。

因此代码如下:

 import java.util.Arrays;

 /**
* @author evasean www.cnblogs.com/evasean/
*/
public class CountInversions {
private static Comparable[] aux;
private static int num = 0; // 逆序对计数 private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
} public static int inversionsNum(Comparable[] a) {
aux = new Comparable[a.length];
sort(a, 0, a.length - 1);
return num;
} private static void sort(Comparable[] a, int lo, int hi) {
if (hi <= lo)
return;
int mid = lo + (hi - lo) / 2;
sort(a, lo, mid);
sort(a, mid + 1, hi);
merge(a, lo, mid, hi);
} private static void merge(Comparable[] a, int lo, int mid, int hi) {
int i = lo;
int j = mid + 1;
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
for (int k = lo; k <= hi; k++) {
if (i > mid) // i>mid表示aux的左半侧已经被全部被放于a中,直接将右半侧部分放入a
a[k] = aux[j++];
else if (j > hi) // j>hi表示aux的右半侧已经被全部被放于a中,直接将左半侧部分放入a
a[k] = aux[i++];
else if (less(aux[j], aux[i])){ // 右侧元素小于左侧元素时,将右侧元素放入
num += mid+1-i; //此时右侧的这个元素a[j]和[a[i],a[mid]]整个区间的元素都是逆序对
a[k] = aux[j++];
}else a[k] = aux[i++];
}
//System.out.println(Arrays.toString(a));
} public static void main(String[] args) {
Integer[] a = { 6,5,2,3,4,1 };
System.out.println(inversionsNum(a));
System.out.println(Arrays.toString(a));
}
}

Coursera Algorithms week3 归并排序 练习测验: Counting inversions的更多相关文章

  1. Coursera Algorithms week3 归并排序 练习测验: Shuffling a linked list

    题目原文: Shuffling a linked list. Given a singly-linked list containing n items, rearrange the items un ...

  2. Coursera Algorithms week3 归并排序 练习测验: Merging with smaller auxiliary array

    题目原文: Suppose that the subarray a[0] to a[n-1] is sorted and the subarray a[n] to a[2*n-1] is sorted ...

  3. Coursera Algorithms week3 快速排序 练习测验: Selection in two sorted arrays(从两个有序数组中寻找第K大元素)

    题目原文 Selection in two sorted arrays. Given two sorted arrays a[] and b[], of sizes n1 and n2, respec ...

  4. Coursera Algorithms week3 快速排序 练习测验: Decimal dominants(寻找出现次数大于n/10的元素)

    题目原文: Decimal dominants. Given an array with n keys, design an algorithm to find all values that occ ...

  5. Coursera Algorithms week3 快速排序 练习测验: Nuts and bolts

    题目原文: Nuts and bolts. A disorganized carpenter has a mixed pile of n nuts and n bolts. The goal is t ...

  6. Coursera Algorithms week1 算法分析 练习测验: Egg drop 扔鸡蛋问题

    题目原文: Suppose that you have an n-story building (with floors 1 through n) and plenty of eggs. An egg ...

  7. Coursera Algorithms week1 算法分析 练习测验: 3Sum in quadratic time

    题目要求: Design an algorithm for the 3-SUM problem that takes time proportional to n2 in the worst case ...

  8. Coursera Algorithms week2 基础排序 练习测验: Dutch national flag 荷兰国旗问题算法

    第二周课程的Elementray Sorts部分练习测验Interview Questions的第3题荷兰国旗问题很有意思.题目的原文描述如下: Dutch national flag. Given ...

  9. Coursera Algorithms week4 基础标签表 练习测验:Inorder traversal with constant extra space

    题目原文: Design an algorithm to perform an inorder traversal of a binary search tree using only a const ...

随机推荐

  1. Ansible实现zabbix服务器agent端批量部署

    项目需求:由于搭建zabbix,需要每台服务器都需要安装监控端(agent)正常的的操作是一台一台去安装,这样确实有点浪费时间,这里为大家准备了一款开源 的自动化运维工具Ansible,相信大家也很熟 ...

  2. 转载:python 日期,季度,年份

    # 这个data_matrix[:,dimen] <= thresh_val 内标会返回data_matrix当中的值符合条件的,返回为True # ret_array 中就会返回 下标为Tru ...

  3. Oracle最大游标数控制

    /************************************************************************ ********* Oracle最大游标数控制 ** ...

  4. HDU - 1087 Super Jumping!Jumping!Jumping!(dp求最长上升子序列的和)

    传送门:HDU_1087 题意:现在要玩一个跳棋类游戏,有棋盘和棋子.从棋子st开始,跳到棋子en结束.跳动棋子的规则是下一个落脚的棋子的号码必须要大于当前棋子的号码.st的号是所有棋子中最小的,en ...

  5. SQL上门2

    SQL高级教程学习 MySQL的字符匹配和其他数据库不同,一下语句查找(第一个字符不是h,第三个字符是m)不能用“!” select * from country where countryname ...

  6. Vue 安装教程

    1.下载node.js https://nodejs.org/en/ 2.检查环境变量: npm init (初始化项目) npm i webpack vue vue-loader 安装依赖: npm ...

  7. jquery源码分析(七)——事件模块 event(二)

    上一章节探讨了事件的一些概念,接下来看下jQuery的事件模块. jQuery对事件的绑定分别有几个API:.bind()/.live()/.delegate()/.on()/click(), 不管是 ...

  8. poj 2031

    #include<stdio.h> #include<math.h> #include<stdlib.h> #define N 200 double co(doub ...

  9. paste deploy初探

    这段时间刚着手开始研究Openstack Swift源码,为后续开发做准备. Swift依据python WSGI规范.WSGI(Web Server Gateway Interface)是Pytho ...

  10. Sencha Touch 2.1 Chart属性中文解释

    图表的几大要素: 1.坐标:上.下.左.右. 坐标的类型,数字.分类... 坐标包含需要显示的坐标值,即绑定的字段 坐标值的样式,比如旋转.字体大小.格式 坐标的最大值.最小值.是否显示网格 坐标旁边 ...