java - 计算快速排序中的比较和交换

标签 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); 
        } 
    } 

最佳答案

您的计数器是正确的。

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

关于java - 计算快速排序中的比较和交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52616840/

相关文章:

java - Swing刷新周期

c - 排序函数的意外行为

java - Elasticsearch : Sorting by nested documents' values

python - 当每个字典都有不同的键时,如何按值对字典列表进行排序?

C++ 快速排序字母数组

java - 为什么 IntelliJ 显示未找到依赖项 'org.slf4j:slf4j-simple:1.7.25'?

java - Maven 与 Ant : exec Command line

java - 将 MySql 日期时间映射到 hibernate

c - 为什么结构体数组的元素不交换?我正在尝试对学生结构数组进行排序。根据卷号

python - 快速排序没有变得更快