Ruby #index方法VS二进制搜索 [英] Ruby#index Method VS Binary Search

查看:127
本文介绍了Ruby #index方法VS二进制搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个元素和一个数组,Ruby #index方法返回数组中元素的位置。我使用二进制搜索实现了自己的索引方法,期望我的索引方法优于内置索引方法。令我惊讶的是,内置的一个在实验中的速度大约是我的三倍。

Given an element and an array, the Ruby#index method returns the position of the element in the array. I implemented my own index method using binary search expecting mine would outperform the built-in one. To my surprise, the built-in one ran approximately three times as fast as mine in an experiment.

任何Rubyist都知道原因吗?

Any Rubyist knows the reason why?

推荐答案

#index 中不是二分搜索,它只是一个简单的迭代搜索。但是,它是用C而不是Ruby实现的,所以自然它可以快几个数量级。

The built-in #index is not a binary search, it's just a simple iterative search. However, it is implemented in C rather than Ruby, so naturally it can be several orders of magnitude faster.

这篇关于Ruby #index方法VS二进制搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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