ROSALIND|Insertion Sort (INS)
求一個整數數列使用 insertion sort 所需的數字交換次數
Given: A positive integer $n \leq 10^3$ and an array $A[1..n]$ of integers.
Return: The number of swaps performed by the insertion sort algorithm on $A[1..n]$.
(https://rosalind.info/problems/ins/)
Insertion sort 的流程很像整理手牌,由左至右逐一檢查數字。如果當前數字比前面的數字小就往前挪,直到所有數字都被排序。
1 | 1. 尋找錯位數字 |
1 | 2. 向前插入(位移兩次) |
1 | 3. 完成排序 |
此題要求計算排序時數字位移的次數,所以在我新增了一個計數器,讓它在每次插入時更新。
1 | def ins(l): |