목차

    Algorithm(알고리즘)/Quick sort 퀵정렬

    4) 퀵정렬로 함수 정렬

    고로케 2021. 5. 14.

    목차

      반응형

      4. 퀵정렬로 함수 정렬

      # 두 요소의 위치를 바꿔주는 helper function
      def swap_elements(my_list, index1, index2):
          my_list[index1],my_list[index2]=my_list[index2],my_list[index1]
          return my_list
      
      
      # 퀵 정렬에서 사용되는 partition 함수
      def partition(my_list, start, end):
          pivot = my_list[end]
          b = 0
          for i in range(start,end):
              if my_list[i] <= pivot:
                  swap_elements(my_list,i,b)
                  b += 1
          swap_elements(my_list,end,b)
      
          return b
      
      # 테스트 1
      list1 = [4, 3, 6, 2, 7, 1, 5]
      pivot_index1 = partition(list1, 0, len(list1) - 1)
      print(list1)
      print(pivot_index1)
      
      # 테스트 2
      list2 = [6, 1, 2, 6, 3, 5, 4]
      pivot_index2 = partition(list2, 0, len(list2) - 1)
      print(list2)
      print(pivot_index2)
      
      # 결과 
      [4, 3, 2, 1, 5, 6, 7]
      4
      [1, 2, 3, 4, 6, 5, 6]
      3


      풀이

       

      반응형