Created
September 15, 2020 12:27
-
-
Save masakih/c0222052d89e220e844980478016a87e to your computer and use it in GitHub Desktop.
ArraySliceを上手に使ったバイナリサーチ #CodePiece
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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