새소식

Algorithm

퀵소트

  • -

Swift

import Foundation

extension Array where Element: Comparable {
  private mutating func partition(_ left: Int, _ right: Int) -> Int {
    var low = left
    var high = right + 1
    let pivot = self[left]
    print("partition(\(left), \(right))")
    
    repeat {
      repeat {
        low += 1
      } while low <= right && self[low] < pivot
      
      repeat {
        high -= 1
      } while high >= left && self[high] > pivot
      print("low: \(low), high: \(high)")
      
      if low < high {
        swapAt(low, high)
        print("swapAt(\(low), \(high))")
      }
    } while low < high
    
    swapAt(left, high)
    print("swapAt(\(left), \(high))")
    return high
  }
  
  private mutating func qsort(_ left: Int, _ right: Int) {
    print("qsort(\(left), \(right))")
    if left < right {
      let pivotIndex = partition(left, right)
      print("pivotIndex: \(pivotIndex)")
      qsort(left, pivotIndex - 1)
      qsort(pivotIndex + 1, right)
    }
  }
  
  mutating func qsort() {
    qsort(0, count - 1)
  }
}
반응형

'Algorithm' 카테고리의 다른 글

DFS와 BFS  (0) 2023.11.09
BFS  (0) 2023.08.03
다익스트라  (0) 2019.06.20
최소 스패닝 트리  (0) 2019.06.20
인덱스 트리  (0) 2019.06.20
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.