Variable a8 and array barray (8.9, 11.3, 9,) which are arranged in order of size. assume that the array length is unknown and the variable value is unknown, how can I quickly find the size of the number a in the ascending order of the array key values? for example: a8, in B [4]... variable a = 8 and array B = array (1, 3, 5, 7, 8.9, 9, 11.3) sorted by size );
If the array length is unknown and the variable value is unknown, the array key values are sorted from small to large.
How to quickly find the value of a between the key name and key name in array B
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) sorted by size );
If the array length is unknown and the variable value is unknown, the array key values are sorted from small to large.
How to quickly find the value of a between the key name and key name in array B
Eg: a = 8, between B [4] and B [5]
Unknown length ............ It's impossible ...... Isn't it B. length ............
Is there any better way to perform this query except for binary ......
You can also encapsulate a class by yourself and map the data by size when the array is created. grouping depends on your requirements, which can greatly improve the speed.
For example, simply Group by integer, as shown in the following code:
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; } }}
The array remains unchanged. just add a hash, which represents the starting subscript of the integer segment. for example, if you want to query the number 8.5, you only need to querythis.hash[Math.floor(8.5)]Andthis.hash[Math.floor(8.5) + 1], The data between two subscripts is enough. if the two hash values are empty, you can find them forward and backward until the values are found. If the data is too sparse, you can create another hash for the hash to record the valid integer segment. it is about changing the space time.
Obviously binary search
Implementation method:
1. sort first (bubble, fast sort, etc.) 2. Insert the elements to be judged, and then sort them. 3. return the key value of the inserted array.