Nodejs Array Search Linear linearSearch(val)

Here you can find the source of linearSearch(val)

Method Source Code

Array.prototype.linearSearch = function(val){

  //my solution//from  w w  w . j a  v  a2 s . c o  m

  // var count = 0;
  // for(var i = 0; i < this.length; i++) {

  //   if(this[i] === val) {
  //     return count;
  //   } 
  //       count++;
  //   if(count === this.length-1) {
  //     return -1;
  //   }
  // }

  //garan's solution
  for (var i = 0; i < this.length; i++) {
    if(this[i] === val) {
      return i
    }
  }
  return -1;
}

Array.prototype.binarySearch = function(val){
  var mid = Math.floor(this.length/2);

  while (val !== this[mid]) {
    if(mid < 0 || mid >= this.length) {
      return -1;
    }
    else if (val > this[mid] ) {
      mid = mid + Math.floor(mid/2)
    }
    else if (val < this[mid] ){
      mid = mid - (Math.floor(mid/2) || 1)
    }
  }
  return mid;
};

module.exports = { Array };

Related

  1. linearSearch(val)
    Array.prototype.linearSearch = function(val){
      for (var i=0; i<this.length; i++) {
        if (this[i] === val) {
          return i;
      return -1;
    };
    
  2. linearSearch(val)
    Array.prototype.linearSearch = function(val){
      for (var i = 0 ; i < this.length; i++) {
        if (this[i] === val)
          return i;
      return -1;
    };
    
  3. linearSearch(val)
    Array.prototype.linearSearch = function(val){
      var answer = this.reduce(function(prev, curr, i){
        if (curr === val) {
          prev = i;
          return prev;
        } else {
          return prev;
      }, -1);
    ...