๐Ÿงผ๋ฒ„๋ธ” ์ •๋ ฌ(bubble sort)

eunseo kim ๐Ÿ‘ฉโ€๐Ÿ’ปยท2021๋…„ 1์›” 4์ผ
0

โœจ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ธฐ๋ณธ

๋ชฉ๋ก ๋ณด๊ธฐ
3/10
post-custom-banner

๐Ÿ“Œ ๋ฒ„๋ธ” ์ •๋ ฌ

  • 2๊ฐœ์˜ ์ธ์ ‘ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ๋น„๊ตํ•ด์„œ ์•ž์— ์žˆ๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ๋’ค์— ์žˆ๋Š” ๋ฐ์ดํ„ฐ๋ณด๋‹ค ํฌ๋ฉด ์ž๋ฆฌ๋ฅผ ๋ฐ”๊พธ๋Š” ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด๋‹ค.


๐Ÿ“Œ ๋ฒ„๋ธ” ์ •๋ ฌ ๊ตฌํ˜„ํ•˜๊ธฐ

๋ฒ„๋ธ” ์ •๋ ฌ์˜ ํŠน์ด์  ํŒŒ์•…ํ•˜๊ธฐ

  • N๊ฐœ์˜ ์›์†Œ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ ์ •๋ ฌ์€ N-1ํ„ด ์ผ์–ด๋‚œ๋‹ค.
  • ์ •๋ ฌ์ด 1ํ„ด ์ผ์–ด๋‚  ๋•Œ๋งˆ๋‹ค ๊ฐ€์žฅ ํฐ ์ˆซ์ž๊ฐ€ ๋’ค์—์„œ๋ถ€ํ„ฐ 1๊ฐœ์”ฉ ๊ฒฐ์ •๋œ๋‹ค.
  • ๋”ฐ๋ผ์„œ ์ •๋ ฌ์ด 1ํ„ด ์ผ์–ด๋‚  ๋•Œ ํ•ด๋‹น ํ„ด ์•ˆ์—์„œ swap์€ N-1-(์ •๋ ฌ๋œ ํ„ด ์ˆ˜) ๋ฒˆ ์‹คํ–‰๋œ๋‹ค.
  • ๋งŒ์•ฝ ์ •๋ ฌ์„ ํ•œ ํ„ด ์‹คํ–‰ํ–ˆ๋Š”๋ฐ swap์ด ํ•œ๋ฒˆ๋„ ์ผ์–ด๋‚˜์ง€ ์•Š์€ ๊ฒฝ์šฐ, ์ด๋ฏธ ์™„์ „ํ•˜๊ฒŒ ์ •๋ ฌ๋œ ์ƒํƒœ์ด๋ฏ€๋กœ ๋” ์ด์ƒ ์ •๋ ฌ์„ ๋ฐ˜๋ณตํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค. ๋”ฐ๋ผ์„œ ๊ฒฝ์šฐ์— ๋”ฐ๋ผ ๋กœ์ง์ด ์ผ์ฐ ๋๋‚  ์ˆ˜๋„ ์žˆ๋‹ค.

๋Œ€๋žต์  ์ฝ”๋“œ

changed = False #swap์ด ์ผ์–ด๋‚ฌ๋Š”์ง€ ๊ฒ€์‚ฌํ•˜๋Š” ๋ณ€์ˆ˜
for index1 in range(๋ฐ์ดํ„ฐ ๊ธธ์ด - 1):
    for index2 in range(๋ฐ์ดํ„ฐ๊ธธ์ด - 1 - index1):
    if list[index2] > list[index2 + 1]:
        swap(list[index2], list[index2 + 1])
        changed = True
    if not changed: # ํ•ด๋‹น ํ„ด์— ํ•œ๋ฒˆ๋„ swap์ด ์ผ์–ด๋‚˜์ง€ ์•Š์œผ๋ฉด ์ด๋ฏธ ์ •๋ ฌ์ด ์™„๋ฃŒ๋œ ์ƒํƒœ์ž„
        break

โœ… Code

def bubblesort(data):
    for index in range(len(data) - 1):
        swap = False
        for index2 in range(len(data) - index - 1):
            if data[index2] > data[index2 + 1]:
                data[index2], data[index2 + 1] = data[index2 + 1], data[index2]
                swap = True
        
        if swap == False:
            break
    return data	

๐Ÿ“Œ ๋ฒ„๋ธ” ์ •๋ ฌ ์‹œ๊ฐ„๋ณต์žก๋„

  • ๋ฐ˜๋ณต๋ฌธ์ด ๋‘ ๊ฐœ์ด๋ฏ€๋กœ O(n2)O(n^2)
  • ์ตœ์•…์˜ ๊ฒฝ์šฐ, nโˆ—(nโˆ’1)2\frac { n * (n - 1)}{ 2 }
  • ์™„์ „ ์ •๋ ฌ์ด ๋˜์–ด ์žˆ๋Š” ์ƒํƒœ๋ผ๋ฉด ์ตœ์„ ์€ O(n)O(n)
profile
์—ด์‹ฌํžˆ๐Ÿ’จ (์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ธ”๋กœ๊ทธ)
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€