我的代碼有什麼問題?我正在從每行包含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
這有什麼錯我的歸併執行?
這裏是我的代碼:
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
@ Ra1nWarden檢查我的編輯請 – fscore
MergeSort.merge(MergeSort.java:67)參考哪一行? – Kakarot