zoukankan      html  css  js  c++  java
  • 求排列的逆序数[归并排序]

    在这里插入图片描述

    #include <iostream>
    #include <string>
    #include <math.h>
    #include<algorithm>
    using namespace std;
    int a[1005];
    int b[1005];
    int num = 0;
    void merge(int a[], int l1, int r1, int l2, int r2)
    {
    	int i = l1, j = l2;
    	int temp[1001], index = 0;
    	while (i <= r1 && j <= r2)
    	{
    		if (a[i] <= a[j])
    			temp[index++] = a[i++];
    		else
    		{
    			temp[index++] = a[j++];
    			num += r1-i+1;
    		}
    	}
    	while (i <= r1)
    		temp[index++] = a[i++];
    	while (j <= r2)
    		temp[index++] = a[j++];
    	for (i = 0; i < index; i++)
    	{
    		a[l1 + i] = temp[i];
    	}
    
    }
    void MergeSort(int a[], int l, int r)
    {
    	if (l >= r)
    		return;
    	int mid = (l+r)/2;
    	MergeSort(a, l, mid);
    	MergeSort(a, mid + 1, r);
    	merge(a, l, mid, mid + 1, r);
    }
    
    int main()
    {
    	int n;
    	cin >> n;
    	for (int i = 0; i < n; i++)
    	{
    		cin >> a[i];
    	}
    	MergeSort(a, 0, n - 1);
    	cout << num << endl;
    }
    
    
  • 相关阅读:
    Java
    HashMap数据结构与实现原理解析(干货)
    Java
    Java
    Java
    面向对象基础
    Java
    Java
    Java
    shell脚本
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13811936.html
Copyright © 2011-2022 走看看