Last active
March 18, 2017 17:59
-
-
Save vitkarpov/6712164e3efece5f7e8aa2e9a07b9b17 to your computer and use it in GitHub Desktop.
"Cracking the coding interview", sorting, 10.1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Сливает два отсортированных массива. | |
* Результат окажется в первом массиве, | |
* в котором есть дополнительное место для второго массива. | |
* | |
* @example | |
* const a = [1,3,4]; | |
* const b = [2,3,5]; | |
* merge(a, b); | |
* // [1,2,3,3,4,5] | |
* console.log(a); | |
* | |
* @param {array} a | |
* @param {array} b | |
*/ | |
function merge(a, b) { | |
// указатель на конец массива a | |
let i = a.length - 1; | |
// указатель на конец массива b | |
let j = b.length - 1; | |
// указатель на конец результирующего массива | |
let end = a.length + b.length - 1; | |
while (j >= 0) { | |
if (i >= 0 && a[i] > b[j]) { | |
a[end] = a[i]; | |
i--; | |
} else { | |
a[end] = b[j]; | |
j--; | |
} | |
end--; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment