为什么在排序列表上运行快速排序时,为什么仍然会有交换?

时间:2018-10-04 19:36:17

标签: java sorting quicksort

当我在我已经按顺序排列的10个整数数组上运行此快速排序时,仍然有20个交换,而我不知道为什么会这样。

public int partition(int array[], int low, int high) 
    { 
        int pivot = array[(low+high)/2];  
        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); 
        } 
    } 

0 个答案:

没有答案