-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0912-sort-an-array.js
More file actions
97 lines (82 loc) · 2.42 KB
/
0912-sort-an-array.js
File metadata and controls
97 lines (82 loc) · 2.42 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* Sort An Array
* Time Complexity: O(n log n)
* Space Complexity: O(n)
*/
var sortArray = function (nums) {
if (nums.length <= 1) {
return nums;
}
const recurseAndSort = (dataSequence, firstIdx, lastIdx) => {
if (firstIdx >= lastIdx) {
return;
}
const dividingPoint = Math.floor((firstIdx + lastIdx) / 2);
recurseAndSort(dataSequence, firstIdx, dividingPoint);
recurseAndSort(dataSequence, dividingPoint + 1, lastIdx);
const combineSortedHalves = (
originalArray,
leftStartPoint,
leftEndPoint,
rightStartPoint,
rightEndPoint,
) => {
const leftSegmentLength = leftEndPoint - leftStartPoint + 1;
const rightSegmentLength = rightEndPoint - rightStartPoint + 1;
const tempLeftStorage = new Array(leftSegmentLength);
const tempRightStorage = new Array(rightSegmentLength);
for (
let copyIndexLeft = 0;
copyIndexLeft < leftSegmentLength;
copyIndexLeft++
) {
tempLeftStorage[copyIndexLeft] =
originalArray[leftStartPoint + copyIndexLeft];
}
for (
let copyIndexRight = 0;
copyIndexRight < rightSegmentLength;
copyIndexRight++
) {
tempRightStorage[copyIndexRight] =
originalArray[rightStartPoint + copyIndexRight];
}
let ptrLeftHalf = 0;
let ptrRightHalf = 0;
let ptrMainArray = leftStartPoint;
while (
ptrLeftHalf < leftSegmentLength &&
ptrRightHalf < rightSegmentLength
) {
if (tempLeftStorage[ptrLeftHalf] <= tempRightStorage[ptrRightHalf]) {
originalArray[ptrMainArray] = tempLeftStorage[ptrLeftHalf];
ptrLeftHalf++;
} else {
originalArray[ptrMainArray] = tempRightStorage[ptrRightHalf];
ptrRightHalf++;
}
ptrMainArray++;
}
while (ptrLeftHalf < leftSegmentLength) {
originalArray[ptrMainArray] = tempLeftStorage[ptrLeftHalf];
ptrLeftHalf++;
ptrMainArray++;
}
while (ptrRightHalf < rightSegmentLength) {
originalArray[ptrMainArray] = tempRightStorage[ptrRightHalf];
ptrRightHalf++;
ptrMainArray++;
}
};
combineSortedHalves(
dataSequence,
firstIdx,
dividingPoint,
dividingPoint + 1,
lastIdx,
);
};
const totalElementsCount = nums.length;
recurseAndSort(nums, 0, totalElementsCount - 1);
return nums;
};