快速排序中的Lomuto分区

时间:2017-07-13 04:31:54

标签: algorithm sorting quicksort

Quick Sort的所有Lomuto Partion实现都有两个交换。我们可以只使用一个交换,并删除for循环外的交换代码吗?当j ==高时,代码可以用arr [i]交换arr [high]。以下是我的代码:

1. Original LomutoPartion() implementation:
    int lomutoPartition(int arr[], int low, int high)
    {   
        int pivot = arr[high]; 
        int i = (low-1);
        for (int j = low; j < high; j++)
        {   
            if (arr[j] <= pivot)
            {   
                i++;
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }

        int temp = arr[high - 1];
        arr[high - 1] = arr[i];
        arr[i] = temp;

        return i;
    }

2. My LomutoPartition() implementation:
    int lomutoPartition(int arr[], int low, int high)
    {   
        int pivot = arr[high]; 
        int i = (low-1);
        for (int j = low; j <= high; j++)
        {   
            if (arr[j] <= pivot)
            {   
                i++;
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
        return i;
    }

0 个答案:

没有答案