Merge Sort 合併排序法
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
合併排序法採用了分治法 ( Divide and Conquer ) 概念,將陣列對半拆開,拆到小陣列只剩一個元素,拆開之後,排序再合併。它的時間複雜度是 。
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
一、步驟觀察
- 將陣列對半拆分至剩一個元素 ( Divide,並使用到 Recursive 的概念 )
- 針對相鄰兩個陣列做完比較後,完成排序與合併 ( Conquer )
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
( 圖片來源 wiki )
二、實際操作
使用哪種資料結構:Array
- 將 left 和 right 作為陣列兩端的索引
- 初始化 left l 等於 0 ; right r 等於 arr.length-1
- 如果 r > l,可以拆分的情況
- 找出中間點,將陣列對半拆開
- 呼叫 mergeSort( ) 處理左邊陣列
- 呼叫 mergeSort( ) 處理右邊陣列
- 呼叫 merge( ),排序並合併兩個陣列
邏輯:
程式碼實作:
三、時間複雜度 Big O
- Merge Sort is θ(nLogn) in all 3 cases ( worst, average and best ) as merge sort always divides the array into two halves and takes linear time to merge two halves.
Drawbacks of Merge Sort
- Slower comparative to the other sort algorithms for smaller tasks.
- Merge sort algorithm requires an additional memory space of 0(n) for the temporary array.
- It goes through the whole process even if the array is sorted.
參考資料: