1. Foreword
Yesterday I encountered a problem about how to solve the connection problem of ordered arrays. This is a very common problem. But the efficiency of the code must be taken into consideration here, because the arrays to be connected are all ordered, which is a very important prerequisite.
2. Simple but inefficient algorithm
The first thing I thought of was to use the built-in concat method and then sort it. This method does not take into account the prerequisite that the array is ordered. The code is as follows:
In order to figure out what algorithm is used for sorting, I specifically looked at the algorithm of the V8 engine (Connection), which probably means that when the length of the array is short, insertion sort is used ( InsertionSort), when the length of the array is long, quick sort (QuickSort) is used. I corrected a misunderstanding I had for a long time. I always thought that sort used bubbling.
3. Method of inserting small values
The general idea is to traverse two arrays at the same time, set two flags (i, j) to record the traversed position, insert the smaller value of the two arrays into the new array, and then set the flag Move forward one position and repeat the comparison until the search values are inserted into the array. The first time I did it, I wrote the wrong judgment conditions, so an infinite loop occurred, which exposed my own algorithmic capabilities.
If you increase the number of arrays, for example, A = [1,5], B = [2,6], C = [ 3,4]....K = [....], find the merged array.
When I was asked this question, my first impression was that it was very similar to the "merge algorithm", but if you want to use the merge algorithm, you don't need the prerequisite that the array is ordered. Then I thought about algorithms such as heap sort and quick sort, but found that the prerequisite of array ordering could not be used effectively, and finally gave up. After the interview, I still had no idea. I thought for a long time and didn’t know how to solve this problem efficiently. When I was about to return to the dormitory, my junior brother said "It's another holiday" and "" woke me up. The code is as follows:
再次使用jsperf对代码的性能进行测试分析,结果请猛击这里.