Insertion 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 →
插入排序法是將陣列中未排序的元素,逐一與排序好的資料作比較。它的時間複雜度是 。
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 →
一、步驟觀察
- 標記第一個元素作為已排序的部分
- 遍歷未排序的部分,作以下動作
- 取第一個未排序的元素
- 與已排序的元素作比較
- 向右移動標記
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
- 將第一個元素標記為已排序
- 遍歷未排序的元素
- 取第一個未排序元素
- 遍歷已排序的元素 (從後到前)
- 如果已排序元素 > 未排序元素
- 否則插入未排序的元素 (原位置或空格)
邏輯:
程式碼實作:
三、時間複雜度 Big O
- 總共比較了 1+2+3+…+(n-1)
- 也就是 n*(n-1)/2
- 時間複雜度會忽略係數,所以為