Skip to content

Instantly share code, notes, and snippets.

@alejandrolechuga
Created May 24, 2017 04:23
Show Gist options
  • Save alejandrolechuga/ce6ceddc805a946086e1f6fcb2820fa4 to your computer and use it in GitHub Desktop.
Save alejandrolechuga/ce6ceddc805a946086e1f6fcb2820fa4 to your computer and use it in GitHub Desktop.
// find min and max within an array
var array = [3,4,5,12,90,23];
// function findMM(a) {
// var min = a[0], max = min;
// for (var i = 2, length = a.length; i < length; i ++) {
// if (a[i] > max) {
// max = a[i];
// } else if (a[i] < min) {
// min = a[i];
// }
// }
// return [min, max];
// }
// console.log(findMM(array));
function findMM (a, low, high) {
low = low || 0;
high = high || (a.length - 1);
var max = a[0];
var min = a[1];
if (high - low <= 0) {
return [min, max];
} else if (high - low === 1) {
// comparision
if (a[high] > a[low]) {
min = a[low];
max = a[high];
} else {
min = a[high];
max = a[low];
}
return [min, max];
} else {
var mid = Math.floor((low + high) / 2);
var mm1 = findMM(a, low, mid);
var mm2 = findMM(a, mid + 1, high);
var min1 = mm1[0];
var max1 = mm1[1];
var min2 = mm2[0];
var max2 = mm2[1];
// comparisions
if (min1 < min2) {
min = min1;
} else {
min = min2;
}
if (max1 > max2) {
max = max1;
} else {
max = max2;
}
return [min, max];
}
}
console.log(findMM(array));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment