斯威夫特:标准二进制数组搜索? [英] Swift: Binary search for standard array?

查看:273
本文介绍了斯威夫特:标准二进制数组搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个排序的数组和想要做的二进制搜索就可以了。

I have a sorted array and want to do binary search on it.

于是我问,如果事情是已经在诸如排序等雨燕库可用?或者是有一种影响无关版本?

So I'm asking if something is already available in Swift library like sort etc.? Or is there a type independend version available?

当然,我可以用我自己写的,但我想,以避免再次重蹈覆辙。

Of course I could write it by my own, but I like to avoid reinventing the wheel again.

推荐答案

答案在这里与提高(通用)

func binarySearch<T:Comparable>(inputArr:Array<T>, searchItem: T)->Int{
    var lowerIndex = 0;
    var upperIndex = inputArr.count - 1

    while (true) {
        var currentIndex = (lowerIndex + upperIndex)/2
        if(inputArr[currentIndex] == searchItem) {
            return currentIndex
        } else if (lowerIndex > upperIndex) {
            return -1
        } else {
            if (inputArr[currentIndex] > searchItem) {
                upperIndex = currentIndex - 1
            } else {
                lowerIndex = currentIndex + 1
            }
        }
    }
}

var myArray = [1,2,3,4,5,6,7,9,10];
var searchIndex = binarySearch(myArray,5);
if searchIndex != -1{
    println("Element found on index: \(searchIndex)");
}

这篇关于斯威夫特:标准二进制数组搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆