DININDU DININDU - 7 months ago 20
Javascript Question

JavaScript while loop doesn't work with condition

I have created function named

getIndex
for get index which i search from the array.

So my problem,

When i changed
while (1)
instead of
while (max < min)
that loop is working, but with condition (
while (max < min)
) it's return -1. But i need condition for check if my search is not present in
data
array. Why it's return -1 with condition?

// assume my array looks-like this.
var data = [1, 2, 3, 4, 5, 7, 8, 9, 10];

function getIndex(search, arr) {
var min, max, guess, count;
min = 0;
max = arr.length - 1;
count = 0;

// If my search is not present in array. Return -1.
while (max < min) {
count++;
guess = Math.floor((min + max) / 2);
if (arr[guess] === search) {
return guess;
} else if (arr[guess] < search) {
min = guess + 1;
} else {
max = guess - 1;
}
}
return -1;
}

getIndex(8, data); // return -1

Answer

Change the while condition to while(max>min)