Classic interview question: merge two ordered arrays into one ordered array.
1. Implementation method:
(1) The while loop iterates through two arrays (generating a new array without destroying the original array). The loop terminates until the calculated indexes of the two arrays (I and j), either of which is greater than the length of the array itself.
(2) Positive contrast, dislocation contrast.
Because both of them are ordered. Therefore, just compare the size according to the element value, and then take the largest value.
If the element value of one array index is smaller than the element value of the other array index, put the smallest value in newArr.
And overlay the index value of the minimum value (column i++);
(3) There are three comparisons of element values (less than, greater than, and equal to).
<, take the value of the element less than, and stack the index less than;
Greater than, take the value of the element less than, stack the index less than;
Is equal to, take both elements, and overlay both indexes;
2, code,
Function mergeSort(arr1, arr2) {var [I,j] = [0,0]; let newArr = []; while(i < arr1.length || j <arr2.length) { if (arr1[i] < arr2[j]) { newArr.push(arr1[i]); i++ } else if (arr1[i] > arr2[j]) { newArr.push(arr2[j]) j++ } else { if(arr1[i]) newArr.push(arr1[i]); if(arr2[j]) newArr.push(arr2[j]); i++; J++}} return newArr} mergeSort (,4,6,7 [2], [1,2,3,5,8,9,10,33,44,49]);Copy the code