快速计算比较和交换

时间:2018-10-02 21:42:54

标签: java sorting quicksort

我正在对从文件中读取的2000个整数进行快速排序,但是我得到的比较和交换次数似乎很高。我的柜台在正确的位置吗?还是排序有问题?

public int partition(int array[], int low, int high) 
    { 
        int pivot = array[high];  
        int i = (low-1); 
        for (int j = low; j < high; j++) 
        {
            compCounter++;
            if (array[j] <= pivot) 
            { 
                i++; 
                int temp = array[i]; 
                array[i] = array[j]; 
                array[j] = temp; 
                SwapCounter++;
            } 
        } 

        int temp = array[i+1]; 
        array[i+1] = array[high]; 
        array[high] = temp; 
        SwapCounter++;

        return i+1; 
    } 

    public void quickSort(int array[], int low, int high) 
    { 
        if (low < high) 
        { 
            int pivotPoint = partition(array, low, high); 
            quickSort(array, low, pivotPoint-1); 
            quickSort(array, pivotPoint+1, high); 
        } 
    } 

1 个答案:

答案 0 :(得分:1)

您的计数器是正确的。

一个简短的建议-将交换代码移到一个单独的函数swap(array,fromIndex,toIndex)

相关问题