java - 快速排序不起作用

标签 java

运行上面的代码时,第一个主元返回为 3。该主元在第一个递归方法中作为 2 传输,但在第二个递归中它不采用值 4。有人可以确定问题所在吗?

  class QuickSortRevision{

   int pivot;

   void QuickSort(int[] arr,int low,int high){

        if(low>=high)
        return;

        pivot = quickSortPivot(arr,low,high);//first execution pivot =3

        QuickSort(arr,low,pivot-1);//this is taking 0,2 as parameter;

        QuickSort(arr,pivot+1,high);//but this is not taking 4,8 as parameter;

   }
   int quickSortPivot(int[] arr,int low,int high){

           int temp,index,partition,lindex,hindex;
           lindex=low;
           hindex=high-1;
           partition = arr[high];
           index=high;
           System.out.println("low : "+low+" high "+high);

           while(lindex!=hindex){

               while(arr[lindex]<partition  && (lindex!=hindex) ){
                 lindex++;
               }   

               while(arr[hindex]>partition && (lindex!=hindex) ){
                 hindex--;
               }
                  if( lindex!=hindex)
                  {

                     temp=arr[lindex];
                     arr[lindex]=arr[hindex];
                     arr[hindex]=temp;
                     lindex++;hindex--;
                 }
           }  
           temp=arr[lindex];
           arr[lindex]=partition;
           arr[index]=temp;

      System.out.println("lindex:  "+lindex);
       return lindex; 
   }

void printArray(int[] arr)
{
  for(int element  : arr)
  System.out.print(" "+element);
}

public static void main(String[] args){

   QuickSortRevision qs = new QuickSortRevision();
   int arr[]={17,41,5,22,54,6,29,3,13};
   qs.QuickSort(arr,0,arr.length-1);
   qs.printArray(arr);

}}

最佳答案

第一次调用 QuickSort 时,类成员 pivot 被分配值 3。然后,对 QuickSort 的递归调用将调用 fastSortPivot,其结果被分配给 pivot(并且进一步递归调用也会修改该值)。当对 Quicksort 的调用返回时,pivot的值已被修改!

您应该将pivot声明为QuickSort方法的变量,而不是QuickSortRevision类的实例变量

PS:函数QuickSort应该被称为quickSort

关于java - 快速排序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37567035/

相关文章:

java - 无法加载资源工厂类 [根异常是 java.lang.ClassNotFoundException : oracle. jdbc.pool.OracleDataSourceFactory

java - 选择 JTabbedPane 选项卡时更改 JFrame 显示

sdk - Java JDK、SDK、SE?

java - 如何使编辑文本可滚动并包含在另一个 ScrollView 中?

java - 通过 onejar 插件使用反射

java - 以编程方式更改联系人图片

java - 从 xml 模式绘制属性 Pane

java - Amazon MySQL RDS 和 Hibernalte

java - 重复 Jubula Testcase 中的 LAST 操作

java - Spring security自定义注销空指针异常