最好時間複雜度:O(n)
最壞時間複雜度:O(n²)
平均時間複雜度:O(n²)
空間複雜度:O(1)
是否為穩定排序:Yes
sort in place:Yes
python 實現:
class Solution:
def insertionSort(self, nums):
"""
:type nums: List[int]
:rtype: void
"""
length = len(nums)
if length <= 1:
return
for i in range(0, length-1):
for j in range(i+1, 0, -1):
# 不用“<=”為了保證排序的穩定性
if nums[j] < nums[j-1]:
nums[j], nums[j-1] = nums[j-1], nums[j]
# 當已排序部分的最大值小於等於本次的取值,本次操作直接中斷
else:
break
return
if __name__ == "__main__":
nums = [1,3,2,4,6,8,4,5,6,7]
s = Solution()
s.insertionSort(nums)
print(nums)
複製程式碼