2013-04-02 18 views
-4

我正在尋找一種有效的方式來排序一個雙打數組。我知道泡泡排序和選擇排序,他們都不夠快。我閱讀了快速排序,但我不明白它是如何工作的。有很多示例源代碼,但它們都很差評論。有人可以向我解釋嗎?如何在沒有庫的情況下高效地對一個雙精度數組進行排序?

+0

你學過二叉樹嗎? – CookieOfFortune

+3

「*有人可以顯示實現*」這不是Stack Overflow **或**作業的好用法。 –

+0

泡泡排序和選擇排序都是'O(n^2)'算法 - 大約可以像排序一樣慢(理性)。有很多更快的'O(n log(n))'算法; [Wikipedia](http://en.wikipedia.org/wiki/Sorting_algorithm)是您研究的一個很好的起點。 [合併排序](http://en.wikipedia.org/wiki/Merge_sort)是一種流行的選擇。 –

回答

1

我在得到關於qsort如何工作的想法後寫了這個。我確實認爲qsort不容易理解。它可能需要一些最優化,並且可能沒有與原始qsort相比,但在這裏。感謝爲此嘗試提供幫助的Peaple。

/*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. 
} 
相關問題