sorting 개념&실습(python) 시리즈😊
sorting 2 - mergesort, quicksort, heapsort
sorting 3 - counting sort, radix sort, topological sort
- 시간복잡도가 최대 인 기본 정렬 알고리즘을 알아봅시다.
출처 : https://gmlwjd9405.github.io/2018/05/10/algorithm-heap-sort.html
[https://dev.to/buurzx/buble-sort-4jkc]
cycle 반복때마다 맨 뒤 값은 하나씩 정렬 완료됨
최악의 경우 모든 item을 swap 해야함!
lis = [9,6,7,3,5]
for m in range(len(lis)-1 , 0, -1):
for n in range(m):
if lis[n]>lis[n+1]:
temp=lis[n]
lis[n]=lis[n+1]
lis[n+1]=temp
# lis[n],lis[n+1] = lis[n+1],lis[n] #pythonic 한 코드
print(lis)
# print(lis)
print(sorted_lis==lis)
>>>
[6, 7, 3, 5, 9]
[6, 3, 5, 7, 9]
[3, 5, 6, 7, 9]
[3, 5, 6, 7, 9]
True
def bubble_sort(arr):
end = len(arr)-1
while end>0 :
last_swap = 0
for n in range(end):
if arr[n]> arr[n+1]:
temp = arr[n]
arr[n] = arr[n+1]
arr[n+1] = temp
last_swap = n
end = last_swap
-> not good!
[https://gmlwjd9405.github.io/2018/05/06/algorithm-bubble-sort.html]
lis = [9,6,7,3,5]
for i in range(len(lis)-1):
min_idx = i
for j in range(i+1,len(lis)):
if lis[j]<lis[min_idx]:
min_idx = j
lis[i],lis[min_idx] = lis[min_idx], lis[i]
print(lis)
print(lis==sorted_lis)
>>>
[3, 6, 7, 9, 5]
[3, 5, 7, 9, 6]
[3, 5, 6, 9, 7]
[3, 5, 6, 7, 9]
True
also -> not good!
[https://algopoolja.tistory.com/19]
lis = [9,6,7,3,5]
for end in range(1,len(lis)):
for i in range(end,0,-1):
if lis[i-1]>lis[i]:
lis[i-1], lis[i] = lis[i], lis[i-1]
print(lis)
print(sorted_lis==lis)
>>>
[3, 6, 7, 9, 5]
[3, 5, 7, 9, 6]
[3, 5, 6, 9, 7]
[3, 5, 6, 7, 9]
True
>>>
[6, 9, 7, 3, 5]
[6, 7, 9, 3, 5]
[6, 7, 9, 3, 5]
[6, 7, 3, 9, 5]
[6, 3, 7, 9, 5]
[3, 6, 7, 9, 5]
[3, 6, 7, 5, 9]
[3, 6, 5, 7, 9]
[3, 5, 6, 7, 9]
[3, 5, 6, 7, 9]
True
정리😘
- 잘 쓰이지는 않음
- 쉬운 알고리즘이고 sorting의 고전 알고리즘