你能帮我找出我在 C# 代码中计算数组反转的错误吗?计数不正确。例如,在数组 {3, 8, 6, 1} 中它应该是 4,但它是 3。但是,它适用于数组 {4, 3, 2, 1} 并显示 6。来自文本文件的每个字符串 ( 1111.txt )程序读取,包含1个数组元素。谢谢你。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace C
{
class Program
{
public static long k1 = 0;
static long Marge_sort(int[] A, int p, int r)
{
int q = p;
if (r <= p) return 0;
q = (p + r) / 2;
C.Program.k1 = Marge_sort(A, p, q);
C.Program.k1 += Marge_sort(A, q + 1, r);
C.Program.k1 += Marge(A, p, q, r);
return C.Program.k1;
}
static long Marge(int[] A, int p, int q, int r)
{
long k1 = 0;
int n1 = q - p+1 ;
int[] L = new int[n1+1];
int n2 = r - q;
int i;
int[] R = new int[n2+1];
for(i=0;i<n1;i++)
{
L[i] = 0;
L[i] = A[p + i ];
}
L[n1] = int.MaxValue;
for (i = 0; i < n2; i++)
{
R[i] = 0;
R[i] = A[q + i+1];
}
R[n2] = int.MaxValue;
int j = 0; i = 0;
for(int k=p;k<=r;k++)
{
if (L[i] <= R[j])
{
A[k] = L[i];
i++;
}
else
{
A[k] = R[j];
j++;
k1 = q - i+1 ;
}
}
return k1;
}
static void Main(string[] args)
{
long k1 = 0;
int leght = 0, el = 0;
int[] Ch = new int[leght];
StreamReader s = File.OpenText(@"D:\1111.txt");//IntegerArray
string read = null;
while ((read = s.ReadLine()) != null)
{
//Console.WriteLine(read);
leght++;
Array.Resize(ref Ch, leght);
Ch[el] = Convert.ToInt32(read);
el++;
}
s.Close();
k1=Marge_sort(Ch, 0, leght-1 );
Console.WriteLine("\n"+k1.ToString());
Console.ReadLine();
}
}
}