簡體   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