简体   繁体   English

在Javascript中在一维数组中查找最小值和最大值之间的值

[英]Finding values between min and max in 1d array in Javascript

I have an array with values and I need to find all values between min and max. 我有一个带有值的数组,我需要找到最小和最大之间的所有值。 I believe I need to construct some kind of search tree, is that correct? 我相信我需要构建某种搜索树,对吗? I want something like: 我想要类似的东西:

var values : number[] = tree.findBetween(min : number, max: number);

The performance of the search is the main criterion. 搜索的性能是主要标准。

Also, I don't need to change the tree (add/remove values) once it is constructed. 另外,构造树后,无需更改树(添加/删除值)。

What is it that I need? 我需要什么? A binary-tree? 二叉树? A balanced search tree? 平衡的搜索树? A static search tree? 静态搜索树?

Where do I start? 我从哪里开始?

Thanks to @bergi for the answer, I really do not need to construct a search tree to perform a binary search on a sorted array, so I should be able to find my values and get the part of the array between them. 感谢@bergi的回答,我真的不需要构造搜索树就可以对排序后的数组执行二进制搜索,因此我应该能够找到我的值并获取它们之间的数组部分。

Just for curiosity, I found an interesting article comparing the performance of the binary search with an ordinary search - loop through the array. 出于好奇,我发现了一篇有趣的文章,比较了二进制搜索和普通搜索的性能-遍历数组。 The article somehow mistakenly includes the time to sort the array into the search time - you are supposed to use the binary search only if you have a sorted array (if you can pre-sort it before of the performance critical period). 文章以某种方式错误地包括了将数组排序到搜索时间中的时间-仅当您具有排序后的数组(如果可以在性能关键时期之前对其进行预排序)时,才应使用二进制搜索。 I run the code with up to some 1e7 items and the binary search on sorted arrays takes 0 milliseconds as compared to tens of milliseconds for simply looping the array. 我运行的代码最多包含1e7个项目,对排序数组的二进制搜索需要0毫秒,而简单循环数组需要数十毫秒。

In the end, this is the fastest implementation of binary search I could find. 最后,这是我能找到的最快的二进制搜索实现。 https://oli.me.uk/2014/12/17/revisiting-searching-javascript-arrays-with-a-binary-search/ https://oli.me.uk/2014/12/17/revisiting-searching-javascript-arrays-with-a-binary-search/

Thanks for everyone's help. 感谢大家的帮助。

Oh, sorry, my Globish sometimes plays tricks on me. 哦,对不起,我的Globish有时会骗我。 Otherwise, I do not see too much where the difficulty is for such a question, but here is always a new answer (hoping that this time I will not be next to the plate) 否则,对于这样的问题,我在困难处看不到太多,但这总是一个新的答案(希望这次我不会在盘子旁边)

outside this : what could it be more faster than a native js method ? 除此之外: 还有什么比本地js方法更快的速度?

 const MaxValue = 50, MinValue = 10 ; let ArrayOrigin = [12, 5, 8, 130, 44, 25, 14, 42, 36 ], ArrayInLimits = ArrayOrigin.filter( elm=> elm>MinValue && elm<MaxValue) ; console.log( ...ArrayInLimits ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM