Anh chị cho em hỏi đoạn code của em bị lỗi java.lang.StackOverflowError, nhưng em không rõ tại sao nó bị vậy?
Trong khi đó nếu em thay pivot = a[left] hay a[(left+right)/2] hay thậm chí là a[left + (int)Math.random(right - left + 1)] thi đều chạy được cả.
Kính mong các anh chị giúp em với ^^.
Code:
import java.util.Random; /** * * @author FaTaToo */ public class middlePivot { public static void main(String[] args){ Random random = new Random(); int[] a = new int[10]; System.out.println("New array: "); for(int i=0; i< a.length; i++){ a[i] = random.nextInt(100); System.out.print(a[i] + " "); } System.out.println(); sort(a); System.out.println("Asrray after sorting: "); for(int i=0; i< a.length; i++){ System.out.print(a[i] + " "); } System.out.println(); } static void sort(int[] a){ sort(a, 0, a.length - 1); } static void sort(int[] a, int left, int right){ int index = partition(a, left, right); if( left < index -1) sort(a, left, index - 1 ); if( right > index) sort(a, index , right); } static int partition(int[] a, int left, int right){ int i= left, j = right; int pivot = a[right]; int temp; while(i <= j){ while(a[i] < pivot) i++; while(a[j] > pivot) j--; if( i <= j) { temp = a[i]; a[i] = a[j]; a[j] = temp; i++; j--; } } return i; } }
Kính mong các anh chị giúp em với ^^.