繁体   English   中英

以快速排序计算比较和交换

[英]Counting the comparisons and swaps in a quick sort

我正在对从文件中读取的 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); 
        } 
    } 

你的计数器是正确的。

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

暂无
暂无

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

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