2 // ArrayExtensions.swift
5 // Created by Hori,Masaki on 2017/03/01.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
13 func appended(_ elem: () -> Element) -> Array {
15 return self + [elem()]
19 infix operator ==? : ComparisonPrecedence
20 func ==? <T: Comparable> (lhv: T, rhv: T) -> ComparisonResult {
28 return .orderedAscending
31 return .orderedDescending
34 extension MutableCollection {
36 private func bsearch(min: Int, max: Int, comparator: (Iterator.Element) -> ComparisonResult) -> Iterator.Element? {
43 let current = min + (max - min) / 2
44 let v = self[self.index(self.startIndex, offsetBy: current)]
45 let compRes = comparator(v)
47 if compRes == .orderedSame {
52 let newMin = (compRes == .orderedAscending) ? current + 1 : min
53 let newMax = (compRes == .orderedDescending) ? current - 1 : max
55 return bsearch(min: newMin, max: newMax, comparator: comparator)
58 func binarySearch(comparator: (Iterator.Element) -> ComparisonResult) -> Iterator.Element? {
60 return bsearch(min: 0, max: self.count - 1, comparator: comparator)