-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththree-num-sort.js
More file actions
72 lines (62 loc) · 1.78 KB
/
three-num-sort.js
File metadata and controls
72 lines (62 loc) · 1.78 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
// THREE NUMBER SORT
// TIME O(n)
// SPACE O(1) where n is the lenght of the array
////////////////////////////////////////////////////////
// function threeNumberSort(array, order) {
// let firstIdx = 0;
// for (let num = 0; num < array.length; num++) {
// if (array[num] === order[0]) {
// swap(firstIdx, num, array);
// firstIdx++;
// }
// }
// let lastIdx = array.length - 1;
// for (let j = array.length - 1; j >= 0; j--) {
// if (array[j] === order[2]) {
// swap(lastIdx, j, array);
// lastIdx--;
// }
// }
// return array;
// }
// function swap(first, second, array) {
// const temp = array[first];
// array[first] = array[second];
// array[second] = temp;
// }
// const array = [1, 0, 0, -1, -1, 0, 1, 1];
// const order = [0, 1, -1];
// console.log(threeNumberSort(array, order));
////////////////////////////////////////////////////////////////
//SOLUTION 2
/// TIME O(n)
// SPACE O(1) where n is the lenght of the array
function threeNumberSort(array, order) {
const firstValue = order[0];
const secondValue = order[1];
let firstIdx = 0;
let secondIdx = 0;
let thirdIdx = array.length - 1;
while (secondIdx <= thirdIdx) {
const value = array[secondIdx];
if (value === firstValue) {
swap(firstIdx, secondIdx, array);
firstIdx++;
secondIdx++;
} else if (value === secondValue) {
secondIdx++;
} else {
swap(secondIdx, thirdIdx, array);
thirdIdx -= 1;
}
}
return array;
}
function swap(first, second, array) {
const temp = array[first];
array[first] = array[second];
array[second] = temp;
}
const array = [1, 0, 0, -1, -1, 0, 1, 1];
const order = [0, 1, -1];
console.log(threeNumberSort(array, order));