Sorting: Insertion Sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
j = i - 1
while j >= 0 and arr[j + 1] < arr[j]:
# arr[j] and arr[j + 1] are out of order so swap them
tmp = arr[j + 1]
arr[j + 1] = arr[j]
arr[j] = tmp
j -= 1
return arr
- Stableity: Stable 안정
- Time Complexity:
- Best: O(n)
- Worst: O(n^2)
- Average: O(n^2)
- Space Complexity: O(1)
'LeetCode > NeetCode' 카테고리의 다른 글
Sorting: Quick Sort ★★★ (0) | 2025.02.04 |
---|---|
Sorting: Merge Sort (1) | 2025.02.03 |
225. Implement Stack using Queues (0) | 2025.02.01 |
1700. Number of Students Unable to Eat Lunch ★ (0) | 2025.02.01 |
Graphs (Union Find): 684. Redundant Connection (1) | 2025.01.28 |