我正在寻找一种对双精度数组进行排序的有效方法。我知道冒泡排序和选择排序,它们似乎都不够快。我读到了快速排序,但我不明白它是如何工作的。有很多示例源代码,但它们都没有得到很好的评论。有人可以向我解释吗?
问问题
196 次
1 回答
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.
}
于 2013-04-03T05:43:14.590 回答