반복적으로 최소값을 찾아 정렬하는 방식
알고리즘 매우 간단. 효율 x 이며 안정성 x
인접한 두개의 데이터를 비교
배열에서 모든 다른 요소들과 교환되어야함
제일 느리지만 단순.
array = [5, 7, 9, 0, 3, 1, 6, 2, 4, 8]
def quick_sort(array):
# 리스트가 하나 이하의 원소를 담고있다면 종료
if len(array) <=1:
return array
pivot = array[0] #피벗
tail = array[1:] #피벗을 제외한 리스트
left_side = [x for x in tail if x<=pivot] # 분할된 왼쪽 부분
right_side = [x for x in tail if x>pivot]
return quick_sort(left_side)+ [pivot] + quick_sort(right_side)
print(quick_sort(array))
array = [7, 5, 9, 0, 3, 1, 6, 2, 9, 1, 4, 8, 0, 5, 2]
count = [0] * (max(array) + 1)
for i in range(len(array)):
count[array[i]] += 1
for i in range(len(count)):
for j in range(count[i]):
print(i, end=" ")
words = ["apple", "banana", "cherry", "date"]
words.sort(key=len)
# Result: ['date', 'apple', 'banana', 'cherry']
tuples = [(1, 'apple'), (3, 'banana'), (2, 'cherry')]
tuples.sort(key=lambda x: x[0]) # Sort by first element
# Result: [(1, 'apple'), (2, 'cherry'), (3, 'banana')]
data = ["item12", "item3", "item23", "item1"]
data.sort(key=lambda x: int(''.join(filter(str.isdigit, x))))
# Result: ['item1', 'item3', 'item12', 'item23']
names = ["alice", "Bob", "david", "Carol"]
names.sort(key=str.lower)
# Result: ['alice', 'Bob', 'Carol', 'david']
class Fruit:
def __init__(self, name, weight):
self.name = name
self.weight = weight
fruits = [Fruit("apple", 180), Fruit("banana", 150), Fruit("cherry", 10)]
fruits.sort(key=lambda fruit: fruit.weight)
# Result: sorted by weight