ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๋ฐ˜์‘ํ˜•

์ •๋ ฌ(sort) ์ด๋ž€?

๋ณต์ˆ˜์˜ ์›์†Œ๋กœ ์ฃผ์–ด์ง„ ๋ฐ์ดํ„ฐ๋ฅผ ์ •ํ•ด์ง„ ๊ธฐ์ค€์— ๋”ฐ๋ผ ์ƒˆ๋กœ ๋Š˜์–ด๋†“๋Š” ์ž‘์—…์ด๋‹ค. ํŒŒ์ด์ฌ์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ด์šฉํ•˜๋ฉด ์ง์ ‘ ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๊ตฌํ˜„ํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค.

  • ํŒŒ์ด์ฌ ๋‚ด์žฅ ํ•จ์ˆ˜ sorted()
  • ๋ฆฌ์ŠคํŠธ์— ์“ธ ์ˆ˜ ์žˆ๋Š” ๋ฉ”์„œ๋“œ .sort()

์ •๋ ฌ์˜ ์ˆœ์„œ๋ฅผ ๋ฐ˜๋Œ€๋กœํ•˜๊ธธ ์›ํ•  ๋•Œ ์ธ์ž๋กœ reverse = True๋ฅผ ๋„ฃ์–ด์ค€๋‹ค.

๋ฌธ์ž์—ด๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฆฌ์ŠคํŠธ์˜ ๊ฒฝ์šฐ ์ •๋ ฌ ์ˆœ์„œ๋Š” ์‚ฌ์ „์ˆœ์„œ(์•ŒํŒŒ๋ฒณ ์ˆœ์„œ)๋ฅผ ๋”ฐ๋ฅธ๋‹ค. ๋ฌธ์ž์—ด ๊ธธ์ด๊ฐ€ ๊ธด ๊ฒƒ์ด๋ผ๊ณ  ํ•ด์„œ ๋” ํฐ ๊ฒƒ์ด ์•„๋‹ˆ๋‹ค. ๋ฌธ์ž์—ด ๊ธธ์ด ์ˆœ์„œ๋กœ ์ •๋ ฌํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ์ •๋ ฌ์— ์ด์šฉํ•˜๋Š” ํ‚ค(key)๋ฅผ ์ง€์ •ํ•ด์ค€๋‹ค.

 

L = ['abcd', 'xyz', 'spam']
# ๋ฌธ์ž์—ด ๊ธธ์ด๋กœ ์ •๋ ฌ
sorted(L, key=lambda x: len(x))


L = [ {'name': 'john', 'score': 88},
    {'name': 'paul', 'score': 92} ]

# ๋ ˆ์ฝ”๋“œ๋“ค์„ ์ด๋ฆ„ ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌ
L.sort(key = lambda x : x['name'])

# ๋ ˆ์ฝ”๋“œ๋“ค์„ ์ ์ˆ˜ ๋†’์€ ์ˆœ์œผ๋กœ ์ •๋ ฌ
L.sort(key=lambda x : x['score'], reverse=True)

 

 

ํƒ์ƒ‰(search) ์ด๋ž€?

๋ณต์ˆ˜์˜ ์›์†Œ๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฐ์ดํ„ฐ์—์„œ ํŠน์ • ์›์†Œ๋ฅผ ์ฐพ์•„๋‚ด๋Š” ์ž‘์—…์œผ๋กœ ์—ฌ๋Ÿฌ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์ด ์žˆ์ง€๋งŒ ์•„์ฃผ ๊ธฐ๋ณธ์ ์ธ ๋‘ ๊ฐ€์ง€๊ฐ€ ์žˆ๋‹ค.

  1. ์„ ํ˜• ํƒ์ƒ‰ (Linear Search) or ์ˆœ์ฐจ ํƒ์ƒ‰ (sequential search) : ์ˆœ์ฐจ์ ์œผ๋กœ ๋ชจ๋“  ์š”์†Œ๋“ค์„ ํƒ์ƒ‰ํ•˜์—ฌ ์›ํ•˜๋Š” ๊ฐ’์„ ์ฐพ์•„๋‚ด๋Š” ๋ฐฉ๋ฒ•, ๋ฐฐ์—ด์˜ ๊ธธ์ด์— ๋น„๋ก€ํ•˜๋Š” ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฌ๋ฏ€๋กœ ์ตœ์•…์˜ ๊ฒฝ์šฐ์—๋Š” ๋ฐฐ์—ด์— ์žˆ๋Š” ๋ชจ๋“  ์›์†Œ๋ฅผ ๋‹ค ๊ฒ€์‚ฌํ•ด์•ผํ•  ์ˆ˜ ์žˆ๋‹ค. O(n)
  2. ์ด์ง„ํƒ์ƒ‰(binary search) : ํƒ์ƒ‰ํ•˜๋ ค๋Š” ๋ฐฐ์—ด์ด ์ด๋ฏธ ์ •๋ ฌ๋˜์–ด์žˆ๋Š” ๊ฒฝ์šฐ์— ์‚ฌ์šฉ, ํฌ๊ธฐ ์ˆœ์œผ๋กœ ์ •๋ ฌ๋˜์–ด์žˆ๋‹ค๋Š” ์„ฑ์งˆ์„ ์ด์šฉํ•ด ํ•œ ๋ฒˆ์— ์ ˆ๋ฐ˜์”ฉ ๋ฐฐ์—ด์„ ์ž˜๋ผ์„œ ๋น„๊ตํ•ด์„œ ์ฐพ๋Š”๋‹ค. ํ•œ ๋ฒˆ ๋น„๊ต๊ฐ€ ์ผ์–ด๋‚  ๋•Œ๋งˆ๋‹ค ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ฐ˜์”ฉ ์ค„์ธ๋‹ค. O(logN)

 

# ์„ ํ˜• ํƒ์ƒ‰
def linear_search(L, x):
    i = 0
    while i < len(L) and L[i] != x:
        i += 1
    if i < len(L):
        return i
    else:
        return -1

# ์ด์ง„ ํƒ์ƒ‰
def binary_search(L, x):
    answer = -1
    
    lower = 0
    upper = len(L) -1
    
    while lower<=upper:
        middle = (lower+upper)//2
        
        if L[middle] == x:
            answer = middle
            break
        elif L[middle] < x:
            lower = middle + 1
            middle = (lower + upper)//2
        else:
            upper = middle -1
            middle = (lower + upper)//2
    
    return answer
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€