Coding Test/알고리즘 이론

Sorting: Insertion Sort

hyunkookim 2025. 2. 3. 17:16

Sorting: Insertion Sort

 

 

https://youtu.be/bPlYH--OYNc

 

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)

'Coding Test > 알고리즘 이론' 카테고리의 다른 글

Sorting: Quick Sort  (0) 2025.02.04
Sorting: Merge Sort  (0) 2025.02.03
BIT 연산 Bit Manipulation  (0) 2025.01.30
다이나믹프로그래밍 DP 2D  (0) 2025.01.30
위상정렬(Topologcal Sort)  (0) 2025.01.27