1

I have implemented Binary Search Algorithm using Node.js. I am recording the time taken by the algorithm to search for a number in a random generated array. I am able to output the time taken by the algorithm for an unsuccessful search.

But I am not able to figure out how to measure the time taken by the algorithm to successfully search a number in an array.

Here is my code -

function binarySearch(A,K)
{
   var l = 0; // min
   var r = A.length - 1; //max
   var n = A.length;
   var time = process.hrtime();

   while(l <= r)
   {
       var m = Math.floor((l + r)/2);

       if(K == A[m])
       {
           return m;
       }
       else if(K < A[m])
       {
           r = m - 1;
       }
       else
       {
           l = m + 1;
       }
   }
   time = process.hrtime(time);
   console.log('%d',time[1]/1000000);
   return -1;
}

var randomlyGenerateArray = function(size)
{
   var array = [];
   for (var i = 0; i < size; i++)
   {
       var temp = Math.floor(Math.random() * maxArrayValue);
       array.push(temp);
   }
   return array;
}

var sortNumber = function(a, b)
{
   return a - b;
}

var program = function()
{
    for (var i = 0; i <= 10000; i += 10)
    {
       var randomArray = randomlyGenerateArray(i);
       var sort = randomArray.sort(sortNumber);
       var randomKey = 100;
       var result = binarySearch(sort, randomKey);
       if(result < 0)
       {
           console.log("Element not found");
       }
       else
       {
           console.log('Element found in position ',result);
       }
    }
}

var maxArrayValue = 1000;

program();

I am using var time = process.hrtime(); to start the timer at the beginning of the algorithm and using time = process.hrtime(time); to end the timer and output it in the console.

How can I measure the time taken by the algorithm to successfully search a number in an array.

Any help would be greatly appreciated.

2
  • 1
    Just copy those same two lines that are before the return -1 to before the other return in the function. Commented May 28, 2016 at 13:14
  • @Pointy Thank You :) It works :) Commented May 28, 2016 at 13:19

1 Answer 1

1

Start your timer before calling the binary search function and end it after the call .. regardless of whether the search is successful or not, you will get the time ..

var time = process.hrtime();
var result = binarySearch(sort, randomKey);
time = process.hrtime(time);
......
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this makes total sense :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.