let findLowIndex = function(arr, key) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
let mid = low + Math.floor((high - low) / 2);
if (mid[arr] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
if (low < arr.length && arr[low] === key) {
return low;
}
return -1;
};
let arr = [1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6]
findLowIndex(arr, 2); //should return 3
Is it okay to use let with mid in while loop? I have modified the above solution from the given answer.
let findLowIndex = function(arr, key) {
let low = 0;
let high = arr.length - 1;
let mid = Math.floor(high / 2);
while (low <= high) {
let midElem = arr[mid];
if (midElem < key) {
low = mid + 1;
} else {
high = mid - 1;
}
mid = low + Math.floor((high - low) / 2);
}
if (low < arr.length && arr[low] === key) {
return low;
}
return -1;
};
let arr = [1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6]
findLowIndex(arr, 2); //should return 3
Which one is better?
Type your question above this line.
Course: https://www.educative.io/collection/5642554087309312/5679846214598656
Lesson: https://www.educative.io/collection/page/5642554087309312/5679846214598656/130003