Java 计数反转挂在终端上
代码针对较小的文件大小运行。但当我使用较大的文件(例如100000)时,它会挂起。使用的代码是:Java 计数反转挂在终端上,java,mergesort,counting,inversion,Java,Mergesort,Counting,Inversion,代码针对较小的文件大小运行。但当我使用较大的文件(例如100000)时,它会挂起。使用的代码是: import java.util.Scanner; import java.util.Formatter; import java.util.NoSuchElementException; import java.lang.IllegalStateException; import java.io.FileNotFoundException; import java.io.*; import jav
import java.util.Scanner;
import java.util.Formatter;
import java.util.NoSuchElementException;
import java.lang.IllegalStateException;
import java.io.FileNotFoundException;
import java.io.*;
import java.lang.*;
public class mergesort1
{
private int arr[];
private int length;
private Scanner sc;
private Formatter f;
public static int inversion=0;
public mergesort1()
{
try
{
sc=new Scanner(new File("IntegerArray.txt"));
}
catch(FileNotFoundException fe)
{
System.err.println("File not found");
}
arr=new int[100000];
length=arr.length;
int i=0;
try
{
while(sc.hasNext())
arr[i++]=sc.nextInt();
}
catch (NoSuchElementException ne)
{
System.err.println("File formed wrong");
sc.close();
System.exit(1);
}
catch(IllegalStateException stateException)
{
System.err.println("Error reading from the file.");
System.exit(1);
}
split(0,length-1);
writeback();
}
private void split(int low,int high)
{
int mid;
if ((high-low)>=1)
{
mid=(low+high)/2;
split(low,mid);
split(mid+1,high);
merge(low,mid+1,high);
}
}
private void merge(int low,int mid,int high)
{
int count=low;
int lcount=low;
int rcount=mid;
int[] merged=new int[length];
while (lcount<=mid-1 && rcount<=high)
{
if (arr[lcount]<arr[rcount])
merged[count++]=arr[lcount++];
else
{
merged[count++]=arr[rcount++];
inversion=inversion+(mid-1-low);
}
}
if (lcount!=mid)
{
while (lcount<=mid-1)
{
if (arr[count]!=count)
merged[count++]=arr[lcount++];
}
}
else
{
while (rcount<=high)
{
if (arr[count]!=count)
merged[count++]=arr[rcount++];
}
}
System.out.println("The inversions counted till now is "+inversion);
for(int i=low;i<=high;i++)
arr[i]=merged[i];
}
private void writeback()
{
try
{
f=new Formatter("output.txt");
}
catch(FileNotFoundException fe)
{
System.err.println("File Not found");
}
for(int i=0;i<arr.length;i++)
f.format("%d\n",arr[i]);
System.out.println("The number of inversions is:"+inversion);
sc.close();
f.close();
}
}
现在,对于2 4 1 3 5的输入,代码运行良好,反转数为3。但是对于计数大小为100000的输入的反转的代码,它在计数后挂起,直到103782637。尝试使用高内存运行
java -Xms512m -Xmx1024m yourclass
我想它不会挂起,只是运行得很慢,因为循环中有很多数据要处理。但是有多慢?它挂起了。你有没有尝试逐步增加数据?不要从2 4 1 3 5跳到1万,而是去1000 3000看看它是如何工作的,mergesort不是最好的排序算法。是的,尝试了100 200,然后是几万。它显示了结果。但对于10万,它只是等待,你尝试了一个系统。out.printlnlow++high;在分割调用之前,看看它在哪里等待?不,现在它只是像以前一样挂起。光标在闪烁