数组中的逆序数(用到归并排序)
来源:互联网 发布:软件hd什么意思 编辑:程序博客网 时间:2024/05/29 17:12
package 数组;
public class InversePairs {
static int count=0;
public static void main(String[] args) {
int[]a={4,2};
Sortmerge(a,0,a.length-1);
System.out.println(count);
}
public static void Sortmerge(int[]a,int start,int end){
int mid=(end+start)/2;
if(start<end){
Sortmerge(a,start,mid);//左边排
Sortmerge(a,mid+1,end);//右边排
merge(a,start,mid,end);//两边一起排
}
}
public static void merge(int[]a,int start,int mid,int end){
int[]b=new int[end-start+1];
int temp=end;
int current=0;
int i=mid;//第一组最后一个数
int j=end;//第二组最后一个数
while(i>=start&&j>=mid+1){
if(a[i]>a[j]){
b[current++]=a[i--];
count+=j-mid;//前面的数大于后面最大的数时,逆序数为后面数个数,如(5,2)(1,3,4)
}else{
b[current++]=a[j--];
}
}
for(;i>=start;i--){//剩前面的数
b[current++]=a[i];
}
for(;j>=mid+1;j--){//剩后面的数
b[current++]=a[j];
}
current=0;
while(temp>=start){//b中的数是降序存储的,要把正序的存回去
a[temp--]=b[current++];
}
}
}
public class InversePairs {
static int count=0;
public static void main(String[] args) {
int[]a={4,2};
Sortmerge(a,0,a.length-1);
System.out.println(count);
}
public static void Sortmerge(int[]a,int start,int end){
int mid=(end+start)/2;
if(start<end){
Sortmerge(a,start,mid);//左边排
Sortmerge(a,mid+1,end);//右边排
merge(a,start,mid,end);//两边一起排
}
}
public static void merge(int[]a,int start,int mid,int end){
int[]b=new int[end-start+1];
int temp=end;
int current=0;
int i=mid;//第一组最后一个数
int j=end;//第二组最后一个数
while(i>=start&&j>=mid+1){
if(a[i]>a[j]){
b[current++]=a[i--];
count+=j-mid;//前面的数大于后面最大的数时,逆序数为后面数个数,如(5,2)(1,3,4)
}else{
b[current++]=a[j--];
}
}
for(;i>=start;i--){//剩前面的数
b[current++]=a[i];
}
for(;j>=mid+1;j--){//剩后面的数
b[current++]=a[j];
}
current=0;
while(temp>=start){//b中的数是降序存储的,要把正序的存回去
a[temp--]=b[current++];
}
}
}
阅读全文
0 0
- 数组中的逆序数(用到归并排序)
- 数组中的逆序对(归并排序)
- 树状数组(归并排序) 之 求逆序数nyoj117
- POJ_3067 Japan[ 逆序数 树状数组 or 归并排序)
- 归并排序&&树状数组求逆序数
- 归并排序 树状数组 求逆序数
- 数组中的逆序对(归并排序+剑指offer)
- 数组中的逆序对(归并排序思想解题)
- 归并排序及延伸(找出数组中的逆序对)
- 数组中的逆序对(归并排序思路)
- 归并排序求数组中的逆序对
- 归并排序-数组中的逆序对
- 数组中的逆序对(归并排序)
- 归并排序,逆序数
- 归并排序 逆序数
- 归并排序+逆序数
- 归并排序 + 逆序数
- 1881: 求逆序数(归并排序求逆序数)
- 宏定义中的特殊参数(#、##、...和__VA_ARGS__)
- Android碎片事务提交transaction.commit()和transaction.commitnow()的区别以及源码完全解析
- HTML-图像的使用(img标签和map标签的使用)
- 算法笔记1
- 使用Thumbnails压缩图片
- 数组中的逆序数(用到归并排序)
- OpenGL:将绘制场景保存为bmp图片
- 【资料合集】阿里巴巴开源技术汇总——内含115个软件与100+技术文档、PDF下载
- 低层视觉:使用一幅图像——纹理
- 统计学习方法——模型的选择与评估(过拟合、泛化能力)
- MyEclipse环境搭建Maven开发环境
- android.view.WindowLeaked:Activity has leaked window DecorView@9a11182[] that was originally added h
- Java多线程总结之聊一聊Queue
- spark2.1源码编译