【发布时间】:2014-08-23 10:38:12
【问题描述】:
我正在阅读 K&R 的 ANSI C。我遇到了 qsort 程序。我需要一点帮助。假设我有 9 个索引为 0->8 的元素。请阅读 cmets 看看我的理解是否正确。非常感谢您的努力
void qsort(int v[] , int left, int right)
{
int i, j, last;
void swap(int v[], int i, int j);
if(left >= right) /*if the array has only one element return it*/
return;
swap(v,left, (left+right)/2); /* now, left=(left+right)/2= 0+8/2= 4 we have 4 as left*/
last= left; /* putting left = last of the first partition group i.e. last=4*/
for(i=left+1; i<=right,i++) /* now looping from 4+1=5 to 8 with increment of 1*/
if(v[i] < v[left]) /*if value at 5th is less than value at 4th */
swap(v, ++last, i);
我在最后一个交换步骤中遇到了问题。正如我的价值观所建议的交换 ++4 即到 i 即 4+1= 5(用 5 交换 5 位置?)。我怎么能理解这个? 4和5之间肯定有交换,不是5和5吗?
代码继续
swap(v,left, last);
qsort(v,left,last-1);
qsort(v,last+1,right);
}
【问题讨论】:
-
我找到了这段代码的演练在这里查看:stackoverflow.com/questions/11939162/…