Skip to content

Instantly share code, notes, and snippets.

@masakih
Created September 15, 2020 12:27
Show Gist options
  • Select an option

  • Save masakih/c0222052d89e220e844980478016a87e to your computer and use it in GitHub Desktop.

Select an option

Save masakih/c0222052d89e220e844980478016a87e to your computer and use it in GitHub Desktop.
ArraySliceを上手に使ったバイナリサーチ #CodePiece
import Foundation
extension Array {
func binarySearch(_ f: (Element) -> ComparisonResult) -> Element? {
self[...].binarySearch(f)
}
}
extension ArraySlice {
func binarySearch(_ f: (Element) -> ComparisonResult) -> Element? {
guard count != 0 else { return nil }
let midIdx = startIndex + ((endIndex - 1) - startIndex) / 2
let mid = self[midIdx]
switch f(mid) {
case .orderedSame:
return mid
case .orderedAscending:
return suffix(from: midIdx + 1).binarySearch(f)
case .orderedDescending:
return prefix(upTo: midIdx).binarySearch(f)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment