Skip to content

Commit 8f50b09

Browse files
Merge pull request #16 from wakidurrahman/feat/merge-sort
feat/merge-sort merge sort implement
2 parents 84dfb9f + a39f92f commit 8f50b09

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Merge sort
3+
*/
4+
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
5+
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
6+
if (ar || !(i in from)) {
7+
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
8+
ar[i] = from[i];
9+
}
10+
}
11+
return to.concat(ar || Array.prototype.slice.call(from));
12+
};
13+
function mergeSort(array) {
14+
if (array.length === 1) {
15+
return array;
16+
}
17+
var center = Math.floor(array.length / 2);
18+
var left = array.slice(0, center);
19+
var right = array.slice(center);
20+
return merge(mergeSort(left), mergeSort(right));
21+
}
22+
function merge(left, right) {
23+
var results = [];
24+
while (left.length && right.length) {
25+
if (left[0] < right[0]) {
26+
results.push(left.shift());
27+
}
28+
else {
29+
results.push(right.shift());
30+
}
31+
}
32+
return __spreadArray(__spreadArray(__spreadArray([], results, true), left, true), right, true);
33+
}
34+
var mergeArray = [3, 4, 6, 9, 3, 1];
35+
console.log(mergeSort(mergeArray));
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Merge sort
3+
*/
4+
5+
type props = number[];
6+
7+
function mergeSort(array: props): (number| undefined)[] | any {
8+
if (array.length === 1) {
9+
return array;
10+
}
11+
const center: number = Math.floor(array.length / 2);
12+
const left: number[] = array.slice(0, center);
13+
const right: number[] = array.slice(center);
14+
return merge(mergeSort(left), mergeSort(right));
15+
}
16+
17+
function merge(left: number[], right: number[]) {
18+
const results: (number| undefined)[] = [];
19+
while (left.length && right.length) {
20+
if (left[0] < right[0]) {
21+
results.push(left.shift());
22+
} else {
23+
results.push(right.shift());
24+
}
25+
}
26+
return [...results, ...left, ...right];
27+
}
28+
29+
const mergeArray = [3, 4, 6, 9, 3, 1];
30+
console.log(mergeSort(mergeArray));

0 commit comments

Comments
 (0)