剑指offer第36题 求逆序数
2015-08-08 11:39
260 查看
#include<iostream> using namespace std; int Merge(int *list,int*copy,int s1,int s2,int end) { int i=s1; int j=s2; int k=s1; int num=0; for(int k=s1;k<=end;k++) copy[k]=list[k]; while(i<=s2-1&&j<=end) { if(copy[i]>copy[j]) { num=num+s2-1-i+1; list[k]=copy[j]; j++; k++; } else { list[k]=copy[i]; i++; k++; } } while(i<=s2-1) { list[k]=copy[i]; i++; k++; } while(j<=end) { list[k]=copy[j]; j++; k++; } return num; } int InverseCore(int *list,int *copy,int start,int end) { if(start==end) return 0; if(start<end) { int mid=(start+end)/2; int left=InverseCore(list,copy,start,mid); int right=InverseCore(list,copy,mid+1,end); int m=Merge(list,copy,start,mid+1,end); return left+right+m; } } int InversePairs(int *list,int length) { if(list==NULL||length<0) return 0; int*copy=new int[length];//copy是辅助空间,作为参数传下去 int count=InverseCore(list,copy,0,length-1); delete[]copy; copy=NULL; return count; } int main() { int a[1000]; int c; int i=0; while(cin>>c) { a[i]=c; i++; if(cin.get()=='\n') break; } cout<<InversePairs(a,i); }
使用递归的归并排序方法
相关文章推荐
- Jquery实现弹性滑块滑动选择数值插件
- js模块化开发
- 剑指offer刷题之java实现的二维数组中的查找
- JQuery兼容IE6问题汇总(不断更新)
- sublime安装less2css,保存less文件同时生成对应css文件
- js 调用打印机(可清除页眉页脚)
- jQuery实现列表内容的动态载入特效
- jQuery实现下拉框选择图片功能实例
- 如何调试Javascript代码
- div+css知识点
- JSON.stringify可以输出格式化的JSON字符串
- JQuery重要知识点
- HTML 显示系统时间
- 利用 Console 来学习、调试JavaScript
- js 事件
- POJ 1274The Perfect Stall
- JS学习笔记(五):关于$(function(){});里面的函数不执行问题
- js 时间戳转为日期
- jQuery实现指定内容滚动同时左侧或其它地方不滚动的方法
- CSS布局自适应等分比例实践