2018-08-08 swift_Binary Search

Binary Search是二分查找,将目标分成两部分来进行查找,相比顺序查找效率要高一些,例如在书店中,20本书里有一本书没有被消磁,按照顺序可能会查到最后第20本才会找到,但是如果分成两部分一次就可以排除10本书,效率提高很多。

func binarySearch<T: Comparable>(_ a: [T], key: T, range: Range<Int>) -> Int? {
    if range.lowerBound >= range.upperBound {
        // If we get here, then the search key is not present in the array.
        return nil
        
    } else {
        // Calculate where to split the array.
        let midIndex = range.lowerBound + (range.upperBound - range.lowerBound) / 2
        
        // Is the search key in the left half?
        if a[midIndex] > key {
            return binarySearch(a, key: key, range: range.lowerBound ..< midIndex)
            
            // Is the search key in the right half?
        } else if a[midIndex] < key {
            return binarySearch(a, key: key, range: midIndex + 1 ..< range.upperBound)
            
            // If we get here, then we've found the search key!
        } else {
            return midIndex
        }
    }
}

let numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67]

binarySearch(numbers, key: 43, range: 0 ..< numbers.count)

在分四次之后找到了43
需要注意的是二分查找的元素是按照顺序排列的

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,923评论 0 33
  • 查找是在大量的信息中寻找一个特定的信息元素,在计算机应用中,查找是常用的基本运算,例如编译程序中符号表的查找。本文...
    北方蜘蛛阅读 3,021评论 1 4
  • MySQL 学习笔记 1 定义 数据库中的表:一行叫一条记录。每一列叫一个属性,或一个字段。主键:表中的某个特殊字...
    U_2647阅读 266评论 0 0
  • 记忆中的村庄,是日落时分的炊烟袅袅;脑海中的村庄,是农忙时候的牛马喧嚣。离开了这么多年,回来后发现,那个曾经风姿绰...
    种花的黄老邪阅读 254评论 1 2
  • 2018年4月8日 星期天 晴 三~四~王宇泽 今天是清明放假后上课的第一天。早上早早起...
    宇泽妈阅读 325评论 0 0

友情链接更多精彩内容