繁体   English   中英

JAVA QUICKSORT…为什么不起作用

[英]JAVA QUICKSORT…why is this not working

为什么此代码不起作用? 以下是快速排序的递归方法。 有人还能建议以支点作为第一个元素的更好的分区算法吗?

import java.util.*;
class QuickSort
{


public static void callQuickSort(int[] array,int left,int right)
{
    if(left<right)
    {
        int s = partition(array,left,right);
        callQuickSort(array,left,s-1);
        callQuickSort(array,s+1,right);     
    }

}

public static int partition(int[] array,int left,int right)
{
    int pI = left;         //pI = partition index
    int pivot = array[right];
    for(int i=left;i<=right-1;i++)
    {
        if(array[i] <= pivot)
        {
            swap(array[i],array[pI]);
            pI++;
        }
    }

    swap(array[pI],array[right]);
    return pI;
}

static void swap(int a,int b)
{
    int temp = a;
    a = b;
    b = temp;
}


public static void main(String args[])
{
    int[] array = {7,2,1,6,8,5,3,4};//array declared
    callQuickSort(array,0,7);      
    System.out.println("Sorted array is - ");
        for(int i=0;i<8;i++)
            System.out.print(array[i]+"\t");
}

}//end of class

输出是

7   2   1   6   8   5   3   4   

上面的代码返回数组,没有任何更改。 为什么数组没有变化?

在Java中,数据是按值而不是按引用传递给方法的,因此您不能像使用交换方法那样使用它。

这是工作代码:

class QuickSort {


    public static void callQuickSort(int[] array, int left, int right) {
        if (left < right) {
            int s = partition(array, left, right);
            callQuickSort(array, left, s - 1);
            callQuickSort(array, s + 1, right);
        }

    }

    public static int partition(int[] array, int left, int right) {
        int pI = left;         //pI = partition index
        int pivot = array[right];
        for (int i = left; i <= right - 1; i++) {
            if (array[i] <= pivot) {
                int temp = array[i];
                array[i] = array[pI];
                array[pI] = temp;
//                swap(array[i], array[pI]);
                pI++;
            }
        }

        int temp = array[pI];
        array[pI] = array[right];
        array[right] = temp;
//        swap(array[pI], array[right]);
        return pI;
    }

    /*static void swap(int a, int b) {
        int temp = a;
        a = b;
        b = temp;
    }*/


    public static void main(String args[]) {
        int[] array = {7, 2, 1, 6, 8, 5, 3, 4};//array declared
        callQuickSort(array, 0, 7);
        System.out.println("Sorted array is - ");
        for (int i = 0; i < 8; i++)
            System.out.print(array[i] + "\t");
    }

}//end of class

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM