4장 버블정렬

버블정렬 알고리즘

버블 정렬 함수 설명


#버블 정렬 함수 구현
def bubble_sort1(list):
    #어떤 인덱스까지 아직 정렬되지 않았는지 기록
    unsorted_until_index = len(list) - 1

    #배열의 정렬 여부를 기록
    sorted = False

    #배열이 완전히 정렬됐음을 알 때까지 while 루프 실행
    while not sorted:

        #for루프는 배열의 첫 인덱스부터 아직 정렬되지 않은 인덱스까지 수행
        for i in range(unsorted_until_index):

            #모든 인접 값 쌍을 비교하고 순서가 뒤바뀌어 있으면 교환
            if list[i] > list[i+1]:
								sorted = False
                list[i], list[i+1] = list[i+1], list[i]

        #unsorted_until_index값을 1 감소
        unsorted_until_index = unsorted_until_index -1
        if unsorted_until_index == 0:
            sorted = True

버블 정렬의 효율

버블 정렬 알고리즘의 두 단계