我正在试着理解一段代码,在下面的代码中&(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);
}发布于 2009-11-01 16:54:18
每次将传递的数组拆分为两个数组时,都会从分区调用Partition方法,一个从当前数组的开头开始,另一个从iLower + 1的索引开始。
&表示(指针)的地址,因此调用&(ipAiLower + 1类似于从索引iLower +1处的单元格insinde ipA的地址调用一个新的数组(C/C++中的指针)。
因为在C中传递数组是通过传递指向其起始位置的指针来完成的,所以它有效地传递了一个以该地址开头的数组。
https://stackoverflow.com/questions/1656681
复制相似问题