Binary Search Array - Node.js Array

Node.js examples for Array:Search

Description

Binary Search Array

Demo Code


function numberLessComparator ( a, b )
{
  return a < b;
}

function numberCmpComparator ( a, b )
{
  return a - b;//from   w w w . j  a v a  2 s . c o m
}

function getCmpFromLessComparator ( lessComparator )
{
  return function ( a, b )
  {
    if ( lessComparator( a, b ) )
      return -1;
    if ( lessComparator( b, a ) )
      return 1;
    return 0;
  };
}

function getLessFromCmpComparator ( cmpComparator )
{
  return function ( a, b )
  {
    return cmpComparator( a, b ) < 0;
  };
}

function sortArray ( array, lessComparator /*= numberLessComparator */ )
{
  array.sort( lessComparator === undefined ? undefined : getCmpFromLessComparator( lessComparator ) );
  return array;
}


function binarySearch ( array, searchVal, lessComparator /*= numberLessComparator */ )
{
  lessComparator = getFirstDefined( lessComparator, numberLessComparator );
  
  var beg = 0;
  var end = array.length;
  
  while (true)
  {
    if ( end === beg )
      return beg;
  
    var mid = div( beg + end, 2 );
    // console.log( 'BINARY_SEARCH', mid );
    
    if ( lessComparator( array[ mid ], searchVal  ) )
      beg = mid + 1;
    else
      end = mid;
  }
}


function binarySearchEnd ( array, searchVal, lessComparator /*= numberLessComparator */ )
{
  lessComparator = getFirstDefined( lessComparator, numberLessComparator );
  
  var beg = 0;
  var end = array.length;
  
  while (true)
  {
    if ( end === beg )
      return beg;
  
    var mid = div( beg + end, 2 );
    
    if ( lessComparator( searchVal, array[ mid ] ) )
      end = mid;
    else
      beg = mid + 1;
  }
}

Related Tutorials