QuickSort implementation does not work for duplicate key

五迷三道 提交于 2020-04-30 06:49:25

问题


I tried to implement Quicksort. It works fine except when there is a duplicate key, in which case there is an infinite loop and it never terminates. Can you help me understand what I am doing wrong?

// quick sort
void quickSort(int arr[], const unsigned size)
{
    // base case
    if (size < 2)
        return;

    int pivot = arr[size / 2];
    unsigned L = 0, U = size - 1;

    // partitioning
    while (L < U) {
        while (arr[L] < pivot)
            L++;
        while (arr[U] > pivot)
            U--;

        swap(&arr[L], &arr[U]);
    }

    quickSort(arr, L); // sort left array
    quickSort(&arr[U + 1], size - L - 1); // sort right array
}

来源:https://stackoverflow.com/questions/61458555/quicksort-implementation-does-not-work-for-duplicate-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!