본문 바로가기

Python_Intermediate/Algorithmus

[알고리즘]버블 정렬(Buble Sort)

반응형

버블 정렬>

두 인접한 데이터를 비교해서, 앞에 있는 데이터가 뒤에 잇는 데이터보다 크면, 자리를 바꾸는 정렬 알고리즘

 

참조 사이트>

https://visualgo.net/bn/sorting

 

VisuAlgo - Sorting (Bubble, Selection, Insertion, Merge, Quick, Counting, Radix)

VisuAlgo is free of charge for Computer Science community on earth. If you like VisuAlgo, the only payment that we ask of you is for you to tell the existence of VisuAlgo to other Computer Science students/instructors that you know =) via Facebook, Twitter

visualgo.net

 

참조 동영상>

정렬 그리기>

데이터 구조가 이렇게 이렇게 되어있다고 생각하면

이를 버블 정렬을 한다고 하면

앞에서 부터 차근 차근 하나씩 비교 해가면서 데이터를 정렬한다.

17 6을 비교해서 17이 크므로 뒤로 보내고 6을 앞으로 보낸다.

이를 반복하여 가장 큰 수가 뒤에 가게 정렬을 한다.

이렇게 정렬을 하면 최종적으로 정렬된것은

위와 같은 데이터 구조가 될것이다.

 

참고 Code>

for index in range(데이터 길이 - 1):
    for index2 in range(데이터길이 - 1):
        if 앞데이터 > 뒤데이터:
            swap(앞데이터, 뒤데이터)

 

Python Code>

def bubbiesort(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

data_list = [17, 6, 8, 11, 2, 3]
print(bubbiesort(data_list))

 

결과값>

[2, 3, 6, 8, 11, 17]

반응형