-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpivot.js
More file actions
46 lines (37 loc) · 938 Bytes
/
pivot.js
File metadata and controls
46 lines (37 loc) · 938 Bytes
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
// First Version
function pivot(arr, start=0, end=arr.length+1){
function swap(array, i, j) {
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
var pivot = arr[start];
var swapIdx = start;
for(var i = start + 1; i < arr.length; i++){
if(pivot > arr[i]){
swapIdx++;
swap(arr,swapIdx,i);
}
}
swap(arr,start,swapIdx);
return swapIdx;
}
// Version with ES2015 Syntax
function pivot(arr, start = 0, end = arr.length - 1) {
const swap = (arr, idx1, idx2) => {
[arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
};
// We are assuming the pivot is always the first element
let pivot = arr[start];
let swapIdx = start;
for (let i = start + 1; i <= end; i++) {
if (pivot > arr[i]) {
swapIdx++;
swap(arr, swapIdx, i);
}
}
// Swap the pivot from the start the swapPoint
swap(arr, start, swapIdx);
return swapIdx;
}
pivot([4,8,2,1,5,7,6,3])