【发布时间】:2014-05-14 21:06:02
【问题描述】:
我的代码有什么问题?我正在从每行包含 1 个数字的文件中读取数据,并使用合并排序对其进行排序。我收到以下错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at MergeSort.merge(MergeSort.java:67)
at MergeSort.sort(MergeSort.java:30)
at MergeSort.main(MergeSort.java:86)
文本文件:
300
40
512
234
100
我的 mergeSort 实现有什么问题吗?
这是我的代码:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MergeSort
{
void sort(int[] arr, int low, int high)
{
if(high > low)
{
int mid = (low + high)/2;
sort(arr,low,mid);
sort(arr,mid+1,high);
merge(arr, low, mid+1, high);
}
}
void merge(int arr[], int low,int mid, int high)
{
int helper[] = new int[arr.length];
//copy both halves into helper
for(int i=0;i< arr.length;i++)
{
helper[i] = arr[i];
}
//compare elements from left & right, initialize variables
int helperLeft = low;
int helperRight = high;
int curr = mid+1;
//while if left<=mid && mid+1 <=right && if left < right assign lowest elem to original array
while(helperLeft <= curr && curr <=helperRight)
{
if(helperLeft <= curr)
{
arr[helperLeft] = helperLeft;
helperLeft++;
}
else
{
arr[curr] = curr;
curr++;
}
helperRight++;
}
//copy all elements to arr
int rem = mid-helperLeft;
for(int i=0;i<rem;i++)
{
arr[helperRight+i] = helper[helperLeft+i];
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
MergeSort pb = new MergeSort();
InputStream inputStream = new FileInputStream("task.txt");
@SuppressWarnings("resource")
BufferedReader R = new BufferedReader(new InputStreamReader(inputStream));
int arraySize = Integer.parseInt(R.readLine());
int[] inputArray = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
inputArray[i] = Integer.parseInt(R.readLine());
}
pb.sort(inputArray, 0, inputArray.length-1);
for (int j = 0; j < inputArray.length; j++) {
System.out.println(inputArray[j]);
}
}
}
新例外:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at coursera.MergeSort.main(MergeSort.java:74)
【问题讨论】:
-
错误在哪一行?
-
@Ra1nWarden 请检查我的编辑
-
MergeSort.merge(MergeSort.java:67) 指的是哪一行?
-
您的文本文件包含什么内容,您也可以发布一下吗
标签: java file sorting bufferedreader mergesort