2016-05-01 170 views
-2

我创建了函数getIndex获取索引,我从数组中搜索索引。JavaScript while while循环不起作用

当我改变了while (1),而不是while (max < min)这个循环是否正常工作,但条件(while (max < min))它的返回-1。但我需要条件检查,如果我的搜索不存在于data阵列中。为什么它返回-1的条件?

// 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 
+1

为什么不你只需要使用'data.indexOf(search)'? –

+1

为什么你使用一种特殊和最糟糕的方式(在时间复杂度方面)来搜索数组? –

回答

1

更改,而条件while(max>min)

1

你在这里做错误.You're检查max小于min或不和,而循环你最小值设置为0,最大值以上阵列的长度。那么Max如何可以小于min?这是正确的,因为条件是错误的,不要进入循环。你需要“最小值小于最大值”或“最大值大于最小值”(都用于同样的目的),条件是它可以正常工作。

1

变化最大和最小的,而状态之间的操作

// assume my array looks-like this. 
var data = [1, 2, 3, 4, 5, 7, 8, 9, 10]; 
debugger; 
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 
0

可以使用for循环,更容易理解

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

 
function getIndex(search, arr) { 
 
    var guess = -1; 
 
    // If my search is not present in array. Return -1. 
 
\t 
 
\t for(var i=0;i<arr.length;i++){ 
 
\t \t if(arr[i]===search)guess = i; 
 
\t } 
 
\t return guess; 
 
} 
 

 
console.log(getIndex(8, data)); // return -1