Linear search algorithm in JavaScript

November 14, 2014

Reading time ~2 minutes

What is linear search algorithm ?

  • find something in order from the beginning of array.

Code

/***************************************
  * 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);

Test

/***************************************
 * 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);

See the Pen Linear search algorithm in JavaScript by Tomoyuki kashiro (@Tkashiro) on CodePen.

add ticket number to git commit automatically

Most of ticket tracker like Github, pivotal tracker have function to connect your commit to ticket(story).But every time when you commit ...… Continue reading

I will build frontend and backend separately

Published on September 28, 2016

order of angular controller's initialisation

Published on October 05, 2015