forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaxRecursive.js
62 lines (51 loc) · 1.56 KB
/
MaxRecursive.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
/**
* Maximum using Division and Conquest
* @param {Array<Number>} vector
* @param {number} start
* @param {number} end
*/
function maxDivisionAndConquest(vector, start, end){
if (start === end) return vector[start];
const middle = parseInt((start + end) / 2);
const aux1 = maxDivisionAndConquest(vector, start, middle);
const aux2 = maxDivisionAndConquest(vector, middle + 1, end);
if (aux1 > aux2) return aux1;
else return aux2;
}
const MAX_LENGTH = 10;
/**
* @param {Array<number>} vector
* @param {number} max
* @param {number} index
*/
function max1(vector, max, index){
if (vector[index] > max) max = vector[index];
if (index < MAX_LENGTH - 1) max = max1(vector, max, index + 1);
return max;
}
/**
* @param {Array<number>} vector
* @param {number} lengthVector
* @returns {number}
*/
function max2(vector, lengthVector){
if (lengthVector === 1) return vector[0];
const max = max2(vector, lengthVector - 1);
if (max > vector[lengthVector - 1]) return max;
else return vector[lengthVector - 1];
}
function main(){
let vector = [];
let values = "[";
for (let index = 0; index < MAX_LENGTH; index++) {
let value = Math.floor(Math.random() * 99); // 0 - 99
vector.push(value);
values += `${value}, `;
}
values += "]"
console.log(values);
console.log('maxDivisionAndConquest => ', maxDivisionAndConquest(vector, 0, MAX_LENGTH -1));
console.log('max1 => ', max1(vector, vector[0], 1));
console.log('max2 => ', max2(vector, MAX_LENGTH));
}
main();