Stackoverflow with Quicksort Java implementation

前端 未结 9 1517
一生所求
一生所求 2020-12-06 19:25

Having some problems implementing quicksort in java. I get a stackoverflow error when I run this program and I\'m not exactly sure why. If anyone can point out the error, it

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 19:57

    You can try this:

    public void sort(int[] A) {
            if (A == null || A.length == 0)
                return;
            quicksort(A, 0, A.length - 1);
        }
    
        public void quicksort(int[] A, int left, int right) {
            int pivot = A[left + (right - left) / 2];
            int i = left;
            int j = right;
            while (i <= j) {
                while (A[i] < pivot) {
                    i++;
                }
                while (A[j] > pivot) {
                    j--;
                }
                if (i <= j) {
                    exchange(i, j);
                    i++;
                    j--;
                }
            }
    
            if(left < j)
                quicksort(A,left,j);
            if(i < right)
                quicksort(A,i,right);
        }
    
        public void exchange(int i, int j){
            int temp=A[i];
            A[i]=A[j];
            A[j]=temp;
        }
    
        public String toString() {
            String s = "";
            s += "[" + A[0];
            for (int i = 1; i < A.length; i++) {
                s += ", " + A[i];
            }
            s += "]";
            return s;
        }
    

    Source: Code 2 Learn: Quick Sort Algorithm Tutorial

提交回复
热议问题