c - 合并排序和反转算法

标签 c mergesort inversion

好的,我的问题是找出给定数组中的反转次数。

看完反转算法后,我想我只需要在几天前写的合并排序算法中添加 1 行代码。

这对于小数组非常有效,但不知何故,当我将数组扩展到 100000 个整数时,答案不正确

这是我添加了那一行的合并函数。

int merge(int arr[],int low,int mid,int high)
{
    int i,j,k;
    int arr1[11];
    int arr2[11];
    for(i=0;i<mid-low+1;i++)
        arr1[i]=arr[low+i];
    for(j=0;j<high-mid;j++)
        arr2[j]=arr[mid+1+j];
    arr1[i]=9999999;
    arr2[j]=9999999;    
    i=0;
    j=0;
    for(k=low;k<=high;k++)
    {
        if(arr1[i]<=arr2[j])
        {
            arr[k]=arr1[i];
            i++;
        }   
        else
        {
            {
                arr[k]=arr2[j];
                j++;
                count=count+mid-low+1-i; //Inversion counter. 
            }
        }       
    }
    return(0);  
}   

谁能告诉我这有什么问题吗?

我花了几个小时试图弄明白,但没有成功。任何输入将不胜感激。谢谢!

最佳答案

long long int count[200200];

int merge()
{
       long long int a[200200],n,left,right,e,i;
       scanf("%lld",&n);
       for( i = 0 ; i< n ; i++)
       {
               scanf("%lld",&a[i]);
               count[i] = 0;
           }
    long long int size,l1,h1,l2,h2,j,k,temp[200200];
    for(size = 1 ; size < n ; size = size *2)
    {
        l1 = 0;
        k = 0;
        while(l1 + size < n)
        {
            h1 = l1 + size - 1;
            l2 = h1 + 1;
            h2 = l2 + size - 1;
            if(h2 >=n )
            h2 = n - 1;
            i =l1;
            j =l2;
            left = count[h1];
            right= count[h2];
            e = 0; 
            while( i <= h1 && j <= h2)
            {
                if(a[i] <= a[j])
                {
                    temp[k++] = a[i++];
                }
                else
                {
                    e = e + h1 - i + 1;
                    temp[k++] = a[j++];
                }
            }
            count[h2] = left + right + e;
            while(i<=h1)
                temp[k++]=a[i++];
            while(j<=h2)
                temp[k++]=a[j++];
            for( i = l1 ; i <= h2 ;i++)
        //    printf("%d ",temp[i]);
        //    printf("\n");
            l1 = h2 + 1;
        }
        for(i = l1 ; k < n ; i++)
        {
            temp[k++] = a[i];
        }
        for( i = 0 ; i < n ; i++)
        {
        //    printf(" %d = %d ",i,count[i]);
            a[i] = temp[i];
        }
    }
    printf("%lld\n\n",count[n-1]);
    return 0;
}



int main()
{

      merge(); 
      return 0;
}

关于c - 合并排序和反转算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9670369/

相关文章:

c - 如何动态地将值从地址分配给指针?

c++ - 将元素分配给数组不起作用(使用 OpenMP 的并行合并排序)

algorithm - 以最少的交换次数重新排序序列以满足偏序约束

c - typedef 结构清晰度

c - 如何修复序列反转程序中的这个段错误?

c++ - 在 C++ 中将数组作为参数传递

algorithm - 为什么在 Matlab 中随着 N 的增加,同一个 N * N 矩阵会得到两个不同的逆矩阵?

python - MATLAB 和 Python 中的逆矩阵结果不同

c - 为什么在 c99 或 c90 模式中支持 _Generic 关键字?

arrays - 合并排序如何处理长度为 N 的数组?