0

该代码运行一个小文件大小。但是当我使用一个大文件时它挂起,比如 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 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 后会挂起。

4

1 回答 1

0

尝试用高内存运行

java -Xms512m -Xmx1024m yourclass
于 2014-06-13T06:35:45.587 回答