본문 바로가기
알고리즘 이론/정렬

버블 정렬(bubble sort)

by bky373 2020. 9. 13.

- given : 인접한 두 데이터를 비교하여, 앞 데이터가 뒤의 데이터보다 크면, 자리를 바꾸는 정렬 알고리즘

def bubblesort(data):
    for index in range(len(data) - 1):
       isSwapped = 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]
               isSwapped = True
        
        if isSwapped == False:
            break
    return data



- when : 10개의 랜덤 수로 실행

import random

data_list = random.sample(range(30), 10)
print(bubblesort(data_list))

 

- then

[0, 2, 4, 5, 10, 11, 16, 17, 21, 28]

 

'알고리즘 이론 > 정렬' 카테고리의 다른 글

합병/병합 정렬(merge sort)  (0) 2020.10.01
퀵 정렬(quick sort)  (0) 2020.09.29
삽입 정렬(insertion sort)  (0) 2020.09.28
선택 정렬(selection sort)  (0) 2020.09.28

댓글