分治法——求逆序数

// test.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include
#include 
using namespace std;

int sum;
int *b;

void merge_sort(int a[], int low, int high);
void merge(int a[], int low, int mid, int high);

void merge_sort(int a[],int low,int high) {
     int mid;
     if (low < high) {
         mid = (low + high) / 2;
         merge_sort(a, low, mid);
         merge_sort(a, mid + 1, high);
         merge(a, low, mid, high);
     }

 }

 void merge(int a[], int low, int mid, int high) {
     int i = low;
     int j = mid + 1;
     int k = 0;

     while (i <= mid && j <= high) {
         if (a[i] <= a[j])
             b[k++] = a[i++];
         else {
             b[k++] = a[j++];
             sum += (mid - i + 1);//此处重难点 画图思考
         }
     }
     while (i <= mid) {
         b[k++] = a[i++];
     }
     while (j <= high) {
         b[k++] = a[j++];
     }
     for (k = 0, i = low; i <= high; i++, k++) {
         a[i] = b[k];
     }
 }
 
int main()
{
    int n, i=0, temp;
    int a[10000];
    cin >> n;
    sum = 0;
    b = new int[n];
    while(cin >> temp && cin.get() != '\n')a[i++] = temp;
    merge_sort(a, 0, n - 1);
    delete[] b;
    cout << sum << endl;
  return 0;
}

在这里插入图片描述

你可能感兴趣的:(算法)