์•Œ๊ณ ๋ฆฌ์ฆ˜

[Algorithm] ํ€ต ์ •๋ ฌ(Quick Sort)

jjingle 2024. 2. 5. 16:55

ํ€ต ์ •๋ ฌ(quick sort) ?

  • ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์˜ ๊ฝƒ
  • ๊ธฐ์ค€์ (pivot)์„ ์ •ํ•ด์„œ, ๊ธฐ์ค€์ ๋ณด๋‹ค ์ž‘์€ ๋ฐ์ดํ„ฐ๋Š” ์™ผ์ชฝ, ํฐ ๋ฐ์ดํ„ฐ๋Š” ์˜ค๋ฅธ์ชฝ์œผ๋กœ ๋ชจ์œผ๋Š” ํ•จ์ˆ˜
  • ๊ฐ ์™ผ์ชฝ, ์˜ค๋ฅธ์ชฝ์€ ์žฌ๊ท€์šฉ๋ฒ•์„ ์‚ฌ์šฉํ•ด์„œ ๋‹ค์‹œ ๋™์ผ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•ด ์œ„ ์ž‘์—… ๋ฐ˜๋ณต
  • ํ•จ์ˆ˜๋Š” ์™ผ์ชฝ(left) + ๊ธฐ์ค€์ (pivot) + ์˜ค๋ฅธ์ชฝ(right)์„ ๋ฆฌํ„ด
def qsort(data):
  if len(data) <= 1:
    return data
  
  pivot = data[0] #๋ฆฌ์ŠคํŠธ ๋งจ ์•ž์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๊ธฐ์ค€์ (pivot)์œผ๋กœ ๋†“๊ธฐ
  
  #1.default
  left, right = list(), list()
  for index in range(1, len(data)):
    if pivot > data[index]:
      left.append(data[index])
    else:
      right.append(data[index])
      
  #2.list comprehension ์‚ฌ์šฉ
  left = [item for item in data[1:] if pivot > item]
  right = [item for item in data[1:] if pivot <= item]
      
  return qsort(left) + [pivot] + qsort(right) #๋ฆฌ์ŠคํŠธ๋ฅผ ๋ง์…ˆ์—ฐ์‚ฐ์„ ํ†ตํ•ด ํ•ฉ์น  ์ˆ˜ ์žˆ๋‹ค