[英]Stack_Overflow_error while calling mergeSort method
我一直在做這個問題:
我創建了一個采用隨機數的文件,並將這些數字存儲在 SinglyLinkedList 數據結構中,我想執行合並排序來對這些隨機數進行排序。
對於較小的輸入,一切正常。 但是當我插入 10000 個數字時,它開始在大約 9800 沒有(僅顯示數字)時給出“stack_overflow”錯誤,當我插入 10 萬個數字時,它運行良好,直到 99700 個數字,然后它開始顯示其余數字的錯誤.
那么這個錯誤背后的確切原因是什么(我知道這是因為它在遞歸函數中丟失了)請在這里幫助我,我無法跟蹤導致此錯誤的問題。
這是我的主要方法代碼:
FileReader fr = new FileReader("C://my_folder//file_List.txt");
BufferedReader br = new BufferedReader(fr);
LinkedListNode lln = new LinkedListNode();
String str;
while((str=br.readLine())!=null){
/* This insertAtEnd appends the number to the SinglyLinkedList*/
lln.insertAtEnd(Integer.parseInt(str));
System.out.println(" "+str);
}
/*This method displays the elements of a LinkedList*/
Node res = lln.traverse();
System.out.println("\n");
mergeSortLinkedList ms = new mergeSortLinkedList();
ms.sort(res);
這是我的排序方法代碼:
public void sort(Node n){
Node tmp = n;
MergeSort(tmp);
}
Node a;
Node b;
public void MergeSort(Node headRef){
Node head1 = headRef;
if(head1 == null || head1.next == null){
return;
}
System.out.print("hi..");
Node Euler = splitList(head1);
printList(Euler);
}
/* perform merge sort on the linked list */
public Node splitList(Node head1){
Node slow;
Node fast;
Node left, right;
if(head1 == null || head1.next == null){
left = head1;
right = null;
return head1;
}
else{
slow = head1;
fast = head1.next;
while(fast!=null){
fast = fast.next;
if(fast!=null){
slow = slow.next;
fast = fast.next;
}
}
left = head1;
right = slow.next;
slow.next = null;
}
return SortedMerge(splitList(left),splitList(right));
}
/* merge the lists.. */
public Node SortedMerge(Node a, Node b){
Node result = null;
if(a == null){
return b;
}
else if( b == null){
return a;
}
if(a.data < b.data){
result = a;
result.next = SortedMerge(a.next, b);//getting error at this line
}
else{
result = b;
result.next = SortedMerge(a,b.next);//getting error at this line
}
return result;
}
public void printList(Node Euler){
System.out.println("\nPrinting sorted elements");
Node Ref = Euler;
int count = 0;
while(Ref!=null){
count++;
System.out.println(count+"-"+Ref.data);
Ref = Ref.next;
}
}
您是否考慮過使用 JDK 中的 Collections.sort(),它將執行合並排序? Java 8 還有一個parallelSort,它執行並行合並排序。
我想給你一個更新。
通過更改堆棧大小,我確實能夠正確運行我的程序。 它Exception in thread "main" java.lang.StackOverflowError
導致Exception in thread "main" java.lang.StackOverflowError
的原因是因為它超出了堆棧大小。
所以我四處尋找並得到了這個解決方案。
轉到項目屬性-內部運行,轉到 VM 選項並將其放入參數 -Xss100m 以使其運行! 現在它能夠對超過 100 萬個數字進行排序:D
歡迎其他建議/解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.