Quick sort - start from the right

Give the code for quick sort first

void quickSort(vector<int> &nums, int left, int right)
{
    if (left > right)
        return;
    int i = left, j = right, temp = nums[left];
    while (i < j)
    {
        while (i < j&&nums[j] >= temp)
            --j;
        while (i < j&&nums[i] <= temp)
            ++i;
        if (i < j)
        {
            nums[i] ^= nums[j];
            nums[j] ^= nums[i];
            nums[i] ^= nums[j];
        }
    }
    nums[left] = nums[i];
    nums[i] = temp;
    quickSort(nums, left, i - 1);
    quickSort(nums, i + 1, right);
}

Use nums[left] as the base temp, and start looking for elements smaller than temp from the right. For nums={4,5,1,2,3}, do a sort, if from right to left first, return {2,3,1,4,5}, from left to right, return {5,3, 1,2,4}. The key is to use the leftmost number nums[left] as the benchmark. Start from the right to ensure that when i and j meet, this number is less than the benchmark. After the exchange, the left side of the temp location is smaller than temp. If starting from the left, the value at the time of encounter is greater than the reference value, and the number on the left of temp cannot be smaller than it. So, to scan, start on the opposite side of the reference number.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325389950&siteId=291194637