-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.insert.js
More file actions
46 lines (42 loc) · 1.2 KB
/
array.insert.js
File metadata and controls
46 lines (42 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
* @title: Insert values into array
* @description: insert given value in ordered sequence
* @author: Thorsten Kober
* @email: [email protected]
*/
function findIndexToInsert(arr, num) {
arr.sort((a, b) => a - b);
let index = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] < num) {
index++;
}
}
return index;
}
function findIndexToInsertBS(arr, value) {
arr.sort((a, b) => a - b);
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const middle = Math.floor((left + right) / 2);
// start with left
if (arr[middle] < value) {
left = middle + 1;
} else {
right = middle - 1;
}
}
return left;
}
// npx jest algorithms/array/array.insert.js
test('findIndexToInsert()', () => {
expect(findIndexToInsert([10, 20, 30, 40, 50], 35)).toEqual(3);
expect(findIndexToInsert([10, 20, 30, 40, 50], 2)).toEqual(0);
expect(findIndexToInsert([10, 20, 30, 40, 50], 60)).toEqual(5);
});
test('findIndexToInsertBS()', () => {
expect(findIndexToInsertBS([10, 20, 30, 40, 50], 35)).toEqual(3);
expect(findIndexToInsertBS([10, 20, 30, 40, 50], 2)).toEqual(0);
expect(findIndexToInsertBS([10, 20, 30, 40, 50], 60)).toEqual(5);
});