-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
94 lines (74 loc) · 1.96 KB
/
index.js
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
/**
* TODO...
*/
const utils = require('./utils.js');
const extractPivot = function extractPivot(array, first, last) {
return first; // TODO Randomize this...
}
const partition = function partition(array, firstIndex, lastIndex, pivotIndex) {
var clone = utils.switchValue(array, pivotIndex, lastIndex),
partitionIndex = firstIndex,
tmpValue;
for (let i = firstIndex; i < lastIndex; i++) {
if (clone[i] <= clone[lastIndex]) {
clone = utils.switchValue(clone, i, partitionIndex);
partitionIndex++;
}
}
clone = utils.switchValue(clone, lastIndex, partitionIndex);
return {
array: clone,
index: partitionIndex
};
};
const generator = function* generator(array, first, last) {
var firstIndex = first || 0,
lastIndex = last || array.length - 1,
clone = array.slice(0),
tmp,
pivotIndex;
if (firstIndex < lastIndex) {
pivotIndex = extractPivot(array, firstIndex, lastIndex);
tmp = partition(array, firstIndex, lastIndex, pivotIndex); // TODO Dirty...
pivotIndex = tmp.index;
clone = tmp.array;
console.log("Index: ", firstIndex, lastIndex);
console.log("Left partition: ", clone, firstIndex, pivotIndex - 1);
console.log("Right partition: ", clone, pivotIndex + 1, lastIndex);
yield *generator(clone, firstIndex, pivotIndex - 1);
yield *generator(clone, pivotIndex + 1, lastIndex);
}
yield {
array: clone
}
}
module.exports = class QuickSort {
constructor(array, pivot) {
this._array = array;
this._pivot = pivot; // TODO Use a random pivot if undefined;
this._steps = [];
}
compute() {
const genObj = generator(this._array);
this._steps = [...genObj];
}
next() {
if (!this._genObj) {
this._genObj = generator(this._array);
}
return this._genObj.next();
}
getStep(no) {
return this._steps[no];
}
get array() {
return this._array;
}
get result() {
const lastStep = this._steps[this._steps.length - 1];
return lastStep ? lastStep.array : undefined;
}
get steps() {
return this._steps;
}
};