用C语言编程的快速排序

用C语言编程的快速排序,c,quicksort,C,Quicksort,我正在读K&R的ANSI C。我偶然发现了qsort程序。我需要一点帮助。假设我有9个索引为0->8的元素。请阅读评论,看看我是否理解正确与否。非常感谢你的努力 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

我正在读K&R的ANSI C。我偶然发现了qsort程序。我需要一点帮助。假设我有9个索引为0->8的元素。请阅读评论,看看我是否理解正确与否。非常感谢你的努力

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);  

首先,您对交换函数有一个小小的误解。假设函数的原型是-

swap(int array[], int i, int j)
swap函数交换位置数组[i]和数组[j]处的数字。因此,swap函数交换数组中的元素。那么,线路呢-

swap(v, left, (left + right) / 2);
last = left;
这意味着,数组中的中间元素与最左边的元素交换。显然,快速排序是以中间元素为轴心。此交换对局部变量或参数没有影响。根据您的数据输入示例,“left”的值为0,而right的值为“8”,即使在交换之后也是如此。这就是你困惑的地方。数组的元素被交换,而不是变量的值。那么,现在,这条线-

swap(v, left, (left + right) / 2);
last = left;
使“last”指向轴的位置(“left”),因此这里的“last”值=0而不是4。所以,循环

for(i = left + 1; i <= right; i++) 
从位置(最后一个+1)到其增量到的任何位置。因此,“last”左边的元素小于pivot,右边的元素大于pivot。我认为您缺少了另一行,在执行算法的过程中,我们将枢轴移回中间位置“v[左]”。然后,递归调用发挥作用。如果您正在寻找有关快速排序的帮助,这是一个很好的起点


我希望我的回答对你有帮助,如果有,请告诉我。。!☺

我找到了这段代码的演练,请在此处检查:
 swap(v, ++last, i);