我正在寻找一种有效的方法来对双打数组进行排序。我知道冒泡排序和选择排序,它们似乎都不够快。我读到了快速排序,但我不明白它是如何工作的。有很多示例源代码,但所有这些都没有得到很好的评论。有人可以向我解释一下吗?
答案 0 :(得分:1)
我在了解了qsort的工作原理之后写了这篇文章。我觉得qsort并不那么容易理解。它可能需要一些优化,并且与原始qsort相比可能没有,但在这里它是。感谢那位试图帮助解决这个问题的人。
/*recursive sorting, throws smaller values to left,
bigger to right side, than recursively sorts the two sides.*/
void sort(double szam[], int eleje, int vege){
if (vege > eleje + 1){ //if I have at least two numbers
double kuszob = szam[eleje]; //compare values to this.
int l = eleje + 1; //biggest index that is on the left.
int r = vege; //smallest index that is on the right side.
while (l < r){ //if I haven't processed everything.
if (szam[l] <= kuszob) l++; //good, this remains on the left.
else
swap(&szam[l], &szam[--r]); //swap it with the farthest value we haven't checked.
}
swap(&szam[--l], &szam[eleje]); //make sure we don't compare to this again, that could cause STACK OVERFLOW
sort(szam, eleje, l); //sort left side
sort(szam, r, vege); //sort right side
}
return; //if I have 1 number break recursion.
}