๊ด€๋ฆฌ ๋ฉ”๋‰ด

๐Ÿฆ• ๊ณต๋ฃก์ด ๋˜์ž!

์ตœ๋‹จ๊ฒฝ๋กœ ํž™์„ ์ด์šฉํ•œ ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ถ”๊ฐ€ ์ •๋ฆฌ...1 ๋ณธ๋ฌธ

Development/CodingTest

์ตœ๋‹จ๊ฒฝ๋กœ ํž™์„ ์ด์šฉํ•œ ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ถ”๊ฐ€ ์ •๋ฆฌ...1

Kirok Kim 2022. 2. 15. 23:40
ํž™ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์‚ฌ์šฉ
# ์ตœ์†Œ ํž™
import heapq

# ์˜ค๋ฆ„์ฐจ์ˆœ ํž™ ์ •๋ ฌ(Heap Sort)
def heapsort(iterable):
	h=[]
	result=[]
	# ๋ชจ๋“  ์›์†Œ๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ํž˜์— ์‚ฝ์ž…
	for value in iterable:
		heapq.heappush(h, value)
	# ํž™์— ์‚ฝ์ž…๋œ ๋ชจ๋“  ์›์†Œ๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ๊บผ๋‚ด์–ด ๋‹ด๊ธฐ
	for i in range(len(h)):
		result.append(heapq.heappop(h))
	return result

result = heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
print(result)

์‹คํ–‰๊ฒฐ๊ณผ
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# ์ตœ๋Œ€ ํž™
import heapq

# ๋‚ด๋ฆผ์ฐจ์ˆœ ํž™ ์ •๋ ฌ(Heap Sort)
def heapsort(iterable):
	h=[]
	result=[]
	# ๋ชจ๋“  ์›์†Œ๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ํž˜์— ์‚ฝ์ž…
	for value in iterable:
		heapq.heappush(h, -value)
	# ํž™์— ์‚ฝ์ž…๋œ ๋ชจ๋“  ์›์†Œ๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ๊บผ๋‚ด์–ด ๋‹ด๊ธฐ
	for i in range(len(h)):
		result.append(-heapq.heappop(h))
	return result

result = heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
print(result)

์‹คํ–‰๊ฒฐ๊ณผ
>>> [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
๋ฐ˜์‘ํ˜•
Comments