Skip to content

Commit 3162ff3

Browse files
committed
choire: find median
1 parent 692bcd6 commit 3162ff3

File tree

3 files changed

+76
-1
lines changed

3 files changed

+76
-1
lines changed

README.md

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@
3434
- [DFS Vs BFS](#dfs-vs-bfs)
3535
- [Sorting](#sorting)
3636
- [Merge Sort](#merge-sort)
37+
- [Implement Merge Sort](#implement-merge-sort)
38+
- [Find Median Values](#find-median-values)
3739
- [Math.floor](#mathfloor)
3840
- [Math.round](#mathround)
3941

@@ -348,7 +350,19 @@ Example: Suppose you have given a tree structure and asked to calculate the aver
348350

349351
Browser's JavaScript Engine (`Array.prototype.sort`) uses merge sort maximum time. Runtime complexity O(n logn), Memory complexity O(n) because we have to create new list. It uses divide-and-conquer algorithm! and also it is recursive.
350352

351-
[Exercise File](src/sorting/merge-sort.mjs)
353+
#### Implement Merge Sort
354+
355+
[Exercise File](src/sorting/merge-sort/merge-sort.mjs)
356+
357+
#### Find Median Values
358+
359+
2 sorted arrays find the median element. Median is the middle index its not an average of values in an sorted array.
360+
361+
![](https://i.imgur.com/anPm3Yx.png)
362+
363+
So in order to find median we can use the stich algorithm since arrays are already sorted. Then we can find the middle index.
364+
365+
[Exercise File](src/sorting/merge-sort/find-median-values.mjs)
352366

353367
## Math.floor
354368

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* 2 sorted arrays find the median element
3+
* It is the middle index its not an average
4+
* [1,5,8,9]
5+
* [2,3,7,10]
6+
*
7+
*/
8+
9+
function stitch(left = [], right = []) {
10+
const results = [];
11+
while (left.length && right.length) {
12+
if (left[0] < right[0]) {
13+
results.push(left.shift());
14+
} else {
15+
results.push(right.shift());
16+
}
17+
}
18+
19+
return [...results, ...left, ...right];
20+
}
21+
22+
function findMedian(left, right) {
23+
const result = stitch(left, right);
24+
return Math.floor(result.length / 2);
25+
}
26+
assert(
27+
[
28+
[1, 5, 8, 9],
29+
[2, 3, 7, 10],
30+
],
31+
findMedian([1, 5, 8, 9], [2, 3, 7, 10]),
32+
4
33+
);
34+
assert(
35+
[
36+
[1, 5, 8, 9],
37+
[2, 3, 7, 10],
38+
],
39+
stitch([1, 5, 8, 9], [2, 3, 7, 10]).toString(),
40+
[1, 2, 3, 5, 7, 8, 9, 10].toString()
41+
);
42+
43+
function assert(given, result, expected) {
44+
if (result === expected) {
45+
console.log('PASS');
46+
} else {
47+
console.log('FAIL');
48+
}
49+
50+
console.log(
51+
'Given: [' +
52+
given +
53+
']' +
54+
'Result: [' +
55+
result +
56+
']' +
57+
'Expected: [' +
58+
expected +
59+
']'
60+
);
61+
}
File renamed without changes.

0 commit comments

Comments
 (0)