快速排序实现问题,数组已排序,但没有退出递归中断条件

时间:2019-05-11 00:40:24

标签: java quicksort

我在下面实现了快速排序算法,该数组已排序,但没有退出递归循环。有人可以在下面分析我的快速排序算法并检查我在做什么错吗?

请在下面查看我的代码:

    package sort;

    import java.util.Arrays;

    public class QuickSort {

       public int array[];

       public void sort(int[] inputArr) {

           if (inputArr == null || inputArr.length == 0) {
               return;
           }
           this.array = inputArr;
           quickSort(0, this.array.length);
       }

        private void quickSort(int low, int high) 
         { 
             if (low < high) 
             {                  
                 int j = partition(low, high); 
                 quickSort(low, j); 
                 quickSort(j+1, high); 
             } 
         } 

       private int partition(int low, int high) { 
           int pivot = this.array[low];
           int i = low;
           int j = high;
           while (i<j) {
               do {
                   i++;
               } while (this.array[i] <= pivot);

               do {
                   j--;            
               } while (this.array[j] > pivot);
           }
           swap(low,j);
           return j;
       }

       private void swap(int i, int j) {
           int temp = this.array[i];
           this.array[i] = this.array[j];
           this.array[j] = temp;
       }

    }

1 个答案:

答案 0 :(得分:1)

Hoare分区方案应类似于或类似(使用中间值作为数据透视):

       private int partition(int low, int high) { 
           int pivot = this.array[low+(high-low)/2];
           int i = low-1;
           int j = high+1;
           while (true) {
               while (this.array[++i] < pivot);   // not <=
               while (this.array[--j] > pivot);
               if(i >= j)
                   return j;
               swap(i,j);
           }
       }