contributed by < chiehen
>
linux2021
程式為單向 linked-list 的 quicksort 實做
主要跟 quick sort 有關的函式有以下:
list_add_node_t
: 將一個 node 加入 list 開頭list_concat
: 將兩個 list 以頭尾相接的方式連接quicksor
: 執行 quicksort 演算法第一次迴圈完:
第二次(全部)迴圈完:
此時 left 中為指向元素(value=5)的next的指標, 透過此指標將 next 中的值改為指向 right 所指向的元素:
result
即為指向連接後 list 開頭的指標
假設有一 list:
到第 10 行結束時將如下:
迴圈中將大於 value 的 node 分到 right, 小於的分到 left,
經過第一次迴圈(line 11 - 15):
結束迴圈:
接著分別排序 right, left
第 23 行前:
第 23 行後:
第 24 行後:
list
變為指向排序完 list 的 pointer to pointer
val
的 node , 並加在 list 前端原先 random() 將 回傳 一個介於 0 to RAND_MAX 的整數, 而根據 維基百科:
The Pseudorandom number generator(PRNG)-generated sequence is not truly random, because it is completely determined by an initial value, called the PRNG's seed (which may include truly random values)
數列將被初始值(initial value)決定, 根據 Linux Programmer's Manual:
The srandom() function sets its argument as the seed for a new sequence
of pseudo-random integers to be returned by random(). These sequences
are repeatable by calling srandom() with the same seed value. If no
seed value is provided, the random() function is automatically seeded
with a value of 1.
因此呼叫 srandom 時設定初始值, 而為了保證初始值不同, 則將現今時間作為初始值:
參考 Optimized QuickSort — C Implementation (Non-Recursive) 實做 non-resursive quick sort。
因為在文章中的資料是以 array 的方式儲存, 如果是 linked-list 在實做上需要 doubly linked list 才有辦法實現, 因此參考課程討論區以 stack 的方式實做 non-resursive quick sort。
定義 stack 結構:
兩個輔助函式對 stack 操作
依 pivot 調整數列的部份, 沿用原先程式的方法, 分為 right
, left
兩個 list。 但在調整完後, 將 right
, pivot
, left
依序推入 stack:
持續將 stack 最頂端的 list 進行 Quick Sort, 如果最頂端的 list 只有一個元素, 則將此元素加到 result
前端, 當 stack 為空時, 代表 sorting 完成:
完整 non-recursive quick sort:
如何改進上述程式碼?
jserv