一个新手C问题

时间:2009-11-01 08:48:43

标签: c arrays

我正在尝试理解代码,究竟是什么 &(ipA[iLower + 1]代表以下代码(快速排序的分区功能?

void Partition(int* ipA, int iSize) {

    // Partitions of size 0 or 1 are already sorted
    if (iSize <= 1) {
        return;
    }

    // Select a pivot from the array randomly
    int iPivot = ipA[rand() % iSize];

    // Indices of the entries to be swapped
    int iLower = 0;
    int iUpper = iSize - 1;

    // Partition array into sections above and below the pivot
    while (iLower < iUpper) {

        while (ipA[iLower] < iPivot) {
            ++iLower;
        }

        while (ipA[iUpper] > iPivot) {
            --iUpper;
        }

        // Swap the entries at the lower and upper indices
        int iTemp       = ipA[iLower];
        ipA[iLower]     = ipA[iUpper];
        ipA[iUpper]     = iTemp;
    }

    // Recursively call partition on each partititon.
    Partition(ipA, iLower);
    Partition(&(ipA[iLower + 1]), iSize - iUpper - 1);
}

1 个答案:

答案 0 :(得分:2)

每次传递的数组从当前数组的开头分割为两个数组,从iLower + 1的索引分割出一个数组时,从分区调用分区方法。

&安培;表示(指针)的地址,因此调用&amp;(ipA [iLower + 1]就像从单元格的地址调用一个新数组(C / C ++中的指针),在索引iLower + 1处输入ipA。
因为在C中传递数组是通过将指针传递给它们的开始来完成的,所以它有效地传递了一个从该地址开始的数组。

相关问题