通过合并排序计算数组中的反转

时间:2014-10-15 13:14:13

标签: c++ arrays algorithm sorting

数组的

反转计数表示 - 数组的排序距离(或接近)。如果数组已经排序,则反转计数为0.如果数组按相反顺序排序,则反转计数最大。

#include <iostream>
#include <cstdlib>
using namespace std;

int merge(int arr[],int temp[], int left, int mid, int right)
{
    int inv_count = 0;
    int i = left;
    int j = mid;
    int k = right;
    while((i <= mid-1) && (j <= right))
    {
        if(arr[i] <= arr[j])
        {
            temp[k++] = arr[i++];
        }
        else
        {
            temp[k++] = arr[j++];
            inv_count += (mid - i);
        }
    }
    while(i <= mid-1)
        temp[k++] = arr[i++];
    while(j <= right)
        temp[k++] = arr[j++];
    for(i = left; i <= right; i++)
        arr[i] = temp[i];
    return inv_count;
}

int _merge_sort(int arr[], int temp[], int left, int right)
{
    int mid, inv_count = 0;
    if(right > left)
    {
        mid = (right+left)/2;
        inv_count = _merge_sort(arr,temp,left,mid);
        inv_count += _merge_sort(arr,temp,mid+1,right);
        inv_count += merge(arr,temp,left,mid+1,right);
    }
    return inv_count;
 }

int merge_sort(int arr[], int array_size)
{
    int *temp = (int *)malloc(sizeof(int)*array_size);
    return (_merge_sort(arr,temp,0,array_size-1));
}

int main()
{
    int arr[]= {1, 25, 12, 56, 36, 3, 0, 10, 8, 7};
    for(int i = 0; i < 10; i++)
        cout<<arr[i]<<"\t";
    cout<<"\n";
    cout<<merge_sort(arr,10)<<"\n";
    for(int i = 0; i < 10; i++)
        cout<<arr[i]<<"\t";
    cout<<"\n";
    return 0;
}

给定数组的预期输出为27但是我得到6.加上我的原始数组数据被修改(它没有排序的值已被更改)。

1 个答案:

答案 0 :(得分:3)

你需要在函数合并中用int k = left替换int k = right。我认为这个数组的预期输出是27.这里讨论了合并排序的各种实现implementing merge sort in C++