<h1>Linear search algorithm in JavaScript
</h1>
<p>Please check javascript code.</p>
/***************************************
* Util
***************************************/
var getRandomNumList = function(num) {
var i, j, tmp, random = new Array(num);
random[0] = 0;
for(i = num - 1; i > 0; i--){
j = Math.floor(Math.random() * (i+1));
tmp = random[i] || i;
random[i] = random[j] || j;
random[j] = tmp;
}
return random;
};
/***************************************
* search
***************************************/
var linearSearch = function(list, target){
var result = null,
i = 0, value;
for(; i < list.length; i++){
value = list[i];
if(value === target){
result = i;
break;
}
}
return result;
};
/***************************************
* main
***************************************/
var list = getRandomNumList(100),
target = 83;
result = linearSearch(list, target);
console.log(list);
console.log('index of tartget(' + target + ') is ' + result);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.