快速排序算法(quickSort)是最常用的排序算法之一。关于其思想讲解建议参考:白话经典算法系列之六 快速排序 快速搞定
文章的思想简而言之就是:分治法 + 挖坑填坑
我简单按照(1)存储数组首数字(2)从后向前比较(3)从前向后比较。这样的顺序写了一个版本:
void quickSort(int* arr, int start, int end)
{
if(start == end) return;
int key = arr[start];
int head = start;
int tail = end;
while(head != tail)
{
while(key < arr[tail]) tail--;
arr[head] = arr[tail];
head++;
while(key > arr[head]) head++;
arr[tail] = arr[head];
tail--;
}
// 此时,head == end
quickSort(arr, start, head - 1);
quickSort(arr, head + 1, end);
return;
}
卧槽完全不对好么,死循环。
检查后发现,是因为自己没有注意到因为key保存了一个值,此时的数组中并没有key值(数组值在动态改变)。不能仅仅依靠与key的大小比较判断内层while的终止点。
需要加上 head < tail 的限制。如此一来,while后的操作也该有所选择。
而且,因为当迭代范围仅剩一个数时,quickSort(arr, start, head - 1); 中start > head - 1,无法跳出迭代。同理,quickSort(arr, head + 1, end); 也是。迭代终点需要修改。
最后,key根本没有放回数组。。。
修改之后的代码为:
void quickSort(int* arr, int start, int end)
{
if(start >= end) return;
int key = arr[start];
int head = start;
int tail = end;
while(head != tail)
{
while(key < arr[tail] && head < tail) tail--;
if(head < tail)
{
arr[head] = arr[tail];
head++;
}
while(key > arr[head] && head < tail) head++;
if(head < tail)
{
arr[tail] = arr[head];
tail--;
}
}
// 此时,head == end
arr[head] = key;
quickSort(arr, start, head - 1);
quickSort(arr, head + 1, end);
return;
}终于对了。。。果然还是需要一个实例运行,来发现问题。原文:http://blog.csdn.net/ironyoung/article/details/40929921