-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMin-and-Max-in-Array-(Optimized).js
More file actions
73 lines (64 loc) · 1.97 KB
/
Min-and-Max-in-Array-(Optimized).js
File metadata and controls
73 lines (64 loc) · 1.97 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
/*
---------------------------------------------------------------
METHOD 2 (Tournament Method)
Divide the array into two parts and compare the maximums
and minimums of the two parts to get the maximum and the
minimum of the whole array.
---------------------------------------------------------------
Pair MaxMin(array, array_size)
if array_size = 1
return element as both max and min
else if arry_size = 2
one comparison to determine max and min
return that pair
else => array_size > 2
recur for max and min of left half
recur for max and min of right half
one comparison determines true max of the two candidates
one comparison determines true min of the two candidates
return the pair of max and min
---------------------------------------------------------------
*/
function getMinMax(arr, low, high) {
const minmax = {};
var minmaxLeft = {};
var minmaxRight = {};
// If there is only one element
if (low === high) {
minmax["min"] = arr[low];
minmax["max"] = arr[low];
return minmax;
}
/* If there are two elements */
if (high === low + 1) {
if (arr[low] > arr[high]) {
minmax["max"] = arr[low];
minmax["min"] = arr[high];
} else {
minmax["max"] = arr[high];
minmax["min"] = arr[low];
}
return minmax;
}
/* If there are more than 2 elements */
var mid = Math.floor((low + high) / 2);
minmaxLeft = { ...getMinMax(arr, low, mid) };
minmaxRight = { ...getMinMax(arr, mid + 1, high) };
/* compare minimums of two parts*/
if (minmaxLeft["min"] < minmaxRight["min"]) {
minmax["min"] = minmaxLeft["min"];
} else {
minmax["min"] = minmaxRight["min"];
}
/* compare maximums of two parts*/
if (minmaxLeft["max"] > minmaxRight["max"]) {
minmax["max"] = minmaxLeft["max"];
} else {
minmax["max"] = minmaxRight["max"];
}
return minmax;
}
var arr = [1000, 11, 445, 1, 330, 3000];
var low = 0;
var high = arr.length - 1;
console.log(getMinMax(arr, low, high));