繁体   English   中英

在使用 Lomuto 算法进行分区的快速排序函数中,“pi+1”语句如何消除尾调用?

[英]How "pi+1" statement does tail call elimination in quicksort function which is using the Lomuto Algorithm for partitioning?

/* 尾调用消除后的快速排序 */

#include<stdio.h>

交换两个元素的实用函数

void swap(int* a, int* b)
{
    int t = *a;
    *a = *b;
    *b = t;
}

/* 此函数以最后一个元素作为主元,将主元元素放置在已排序数组中的正确位置,并将所有较小(小于主元)的元素放在主元的左侧,将所有较大的元素放在主元的右侧。 它使用 Lomuto 分区算法。 */

int partition (int arr[], int low, int high)
{
    int pivot = arr[high];    `// pivot`
    int i = (low - 1);  `// Index of smaller element`

    for (int j = low; j <= high- 1; j++)
    {
        `// If the current element is smaller than or equal to pivot `
        if (arr[j] <= pivot)
        {
            i++;    `// increment index of smaller element`
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}

/*实现QuickSort的main函数arr[] -->要排序的数组,低-->起始索引,高-->结束索引*/

void quickSort(int arr[], int low, int high)
{
    while (low < high)
    {
        `/* pi is partitioning index, arr[p] is now at right place */`
        int pi = partition(arr, low, high);

        `// Separately sort elements before partition and after partition`
        quickSort(arr, low, pi - 1);

        low = pi+1;
    }
}

打印数组的函数

void printArray(int arr[], int size)
{
    for (int i=0; i < size; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

测试以上功能的驱动程序

int main()
{
    int arr[] = {10, 7, 8, 9, 1, 5};
    int n = sizeof(arr)/sizeof(arr[0]);
    quickSort(arr, 0, n-1);
    printf("Sorted array: \n");
    printArray(arr, n);
    return 0;
}

“pi+1”语句如何在quicksort函数中消除尾调用

它没有。 所有主流 x86 编译器都无法从您的代码中展开递归。 例如 gcc -O3 ( Godbolt ):

quickSort:
        cmp     esi, edx
        jge     .L6
        push    r13
        mov     r13, rdi
        push    r12
        mov     r12d, edx
        push    rbp
        mov     ebp, esi
        push    rbx
        sub     rsp, 8
.L3:
        mov     esi, ebp
        mov     edx, r12d
        mov     rdi, r13
        call    partition
        mov     esi, ebp
        mov     rdi, r13
        mov     ebx, eax
        lea     edx, [rax-1]
        call    quickSort     // recursive call
        lea     ebp, [rbx+1]
        cmp     r12d, ebp
        jg      .L3
        add     rsp, 8
        pop     rbx
        pop     rbp
        pop     r12
        pop     r13
        ret

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM