你能幫我找到一個錯誤在我的代碼在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();
}
}
}
你可以改進格式? –
例如,在數組{3,6,8,1}中它應該是4,但它是3.我認爲它應該只有3。 (3,1),(6,1),(8,1) – cvraman
對不起,我的意思是{3,8,6,1} –