查找逆序对很简单,自己变成就是几行,思路也是十分简单。但是题目要求用递归的方法,和合并排序很相似,网上也有很多人提供具体的程序,但是我对这种递归排序还是不能清晰得理解,所以在这里就不贴出来了,只放上了自己写的很low的算法实现代码。
public class inversion {
public static void find_inversion(ArrayList a) {
// 查找数组逆序对的java实现(自己的方法)
int num = 0;
for(int i =0;i
for(int j =i+1;j
if(a.get(i)>a.get(j)){
System.out.print("("+a.get(i)+","+a.get(j)+") ");
num++;
}
}
}
System.out.println("");
System.out.println("逆序对个数:"+num);
}
public static void main(String[] args) {
// 测试查找逆序对
ArrayList a = new ArrayList();
//从控制台获取要排序的数,“#”键结束
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()){
if(sc.equals("#")){
break;
}
a.add(sc.nextInt());
}
find_inversion(a);
}
}
?