Variable A = 8 and array b = Array (1,3,5,7,8.9,9,11.3) that have been arranged in size order;
Suppose the array length is unknown, the value of the variable is unknown, and the array key values are arranged from small to large.
How to quickly find the size of quantity a in, array B between the key name and the key name
Eg:a=8, between B[4] and B[5]
Reply content:
Variable A = 8 and array b = Array (1,3,5,7,8.9,9,11.3) that have been arranged in size order;
Suppose the array length is unknown, the value of the variable is unknown, and the array key values are arranged from small to large.
How to quickly find the size of quantity a in, array B between the key name and the key name
Eg:a=8, between B[4] and B[5]
The length is unknown ..... It's not likely ... No, it's the b.length, it's finished ...
Is there any better way to do this kind of query than just two points ...
Or you encapsulate a class, when the array is set up to do a map, the data grouped by size, how to group to see your requirements, can greatly improve the speed.
For example, simple, grouped by integers, like this:
class ClassA extends Array { constructor(...args) { super(...args); this.hash = []; for(let i = 0; i < this.length; i++) { if(!this.hash[Math.floor(this[i])]) this.hash[Math.floor(this[i])] = i; } }}
Array or that array does not change, just add a hash, which represents the beginning of the integer field subscript, for example, you want to query 8.5 this number, then only need to query this.hash[Math.floor(8.5)]
and this.hash[Math.floor(8.5) + 1]
, two subscript between the data on the line, if the two hash inside is empty, then the separate forward, looking back on the line, Until the value is found. If the data is too sparse, then you can give the hash to make a hash, record the effective integer segment, anyway, is the space to change time.
Clear use of binary search
Implementation method:
1、先排序(冒泡、快速排序等,本题已优先排列好)2、插入需要判断的元素,再排序3、返回插入数组所在的键值