๐ ๋ฒ๋ธ ์ ๋ ฌ(Bubble Sort)
arr = [9,8,7,6,5,4,3,2,1]
def bubble_sort(arr):
n = len(arr)
for i in range(n-1):
for j in range(n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
๐ ์ ํ ์ ๋ ฌ(Selection Sort)
arr = [8,4,6,2,9,1,3,7,5]
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
arr[i], arr[min_index] = arr[min_index], arr[i]
๐ ์ฝ์ ์ ๋ ฌ(Insertion Sort)
arr = [8,4,6,2,9,1,3,7,5]
def insertions_sort(arr):
n = len(arr)
for i in range(1, n):
for j in range(i, 0, -1):
if arr[j-1] > arr[j]:
arr[j-1], arr[j] = arr[j], arr[j-1]
๐ ๋ณํฉ ์ ๋ ฌ(Merge Sort)
arr = [8,4,6,2,9,1,3,7,5]
def merge_sort(arr):
if len(arr) < 2:
return arr
mid = len(arr) // 2
low_arr = merge_sort(arr[:mid])
high_arr = merge_sort(arr[mid:])
merge_arr = []
l, h = 0, 0
while l < len(low_arr) and h < len(high_arr):
if low_arr[l] < high_arr[h]:
merge_arr.append(low_arr[l])
l += 1
else:
merge_arr.append(high_arr[h])
h += 1
merge_arr += low_arr[l:]
merge_arr += high_arr[h:]
return merge_arr
๐ ํต ์ ๋ ฌ(Quick Sort)
arr = [8,4,6,2,9,1,3,7,5]
def quick_sort(arr):
if len(arr) < 1:
return arr
pivot = len(arr) // 2
f_arr, p_arr, b_arr = [], [], []
for value in arr:
if value < arr[pivot]:
f_arr.append(value)
elif value > arr[pivot]:
b_arr.append(value)
else:
p_arr.append(value)
return quick_sort(f_arr) + quick_sort(p_arr) + quick_sort(b_arr)
๐ sort() VS sorted()
โญ K๋ฒ์งธ์
โญ ๊ฐ์ฅ ํฐ ์
โญ H-Index