파이썬 알고리즘
정렬 알고리즘
버블 정렬 (Bubble Sort)
n번 값과 n+1번 값을 비교해서 높은 값을 뒤로 보낸다.
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
#Swap
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
data = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(data)
선택 정렬 (Selection Sort)
전체를 순회해서 최소값을 찾은 다음, 맨 앞의 값과 최소값의 위치를 바꾼다.
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
# Swap with the minimum
arr[i], arr[min_index] = arr[min_index], arr[i]
data = [29, 10, 14, 37, 13]
selection_sort(data)