使用快排和归并求解逆序对

The attached file Q8.txt contains 100,000 integers between 1 and 100,000 (each row has a single integer), the order of these integers is random and no integer is repeated.

  1. Write a program to implement the Sort-and-Count algorithms in your favorite language, find the number of inversions in the given file.
  2. In the lecture, we count the number of inversions in O(nlogn) time, using the Merge-Sort idea. Is it possible to use the Quick-Sort idea instead ?

If possible, implement the algorithm in your favourite language, run it over the given file, and compare its running time with the one above. If not, give a explanation



1. 归并法


最终逆序对的个数是:2500572073

这里写图片描述

归并法的核心就是通过讲子问题划分成一个一个小的问题后进行合并求解。首先对整个数组一直对半的进行划分,一直分到只剩1个为止开始排序并合并,如上图所示。

具体算法如下。从第74行开始计算将要合并的两个子数组的逆序对数,如果左边数组的的一个值是大于右边数组中的数的,则说明左边数组中这个数的后面所有的数字都是大于右边数组的这个数字的(因为在合并时,左右两边数组都已经是有序的),因此直接加 (mid - left + 1 - i) 就可以了,然后一层一层的向上计算过去,即得到了逆序对数。

因为老师有让对比归并法和快排法的效率,因此中间有计算时间的。


#include<cstdio>
#include<cstdlib>
#include<string.h> 
#include<sys/time.h>
#include<iostream>
#include<fstream>
#define MAXN 100001
using namespace std;

double SortAndCount(int left, int right);
double MergeAndCount(int left, int mid, int mid1, int right);

//int num[] = {2, 4, 1, 3, 5};
//int num[] = {4, 7, 6, 3, 1, 2, 9, 8, 5};
int num[MAXN];

int main()
{
    char n[15];
    int i = 0;
    double ans;
    struct timeval t_start, t_end;

    //open the file 
    ifstream in("Q8.txt", ios::in);
    if (!in.is_open()) {
        <
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值