Dazzler - 4 months ago 14x

Node.js Question

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

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();`

`time = process.hrtime(time);`

How can I measure the time taken by the algorithm to

Any help would be greatly appreciated.

Answer

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);
......
```

Source (Stackoverflow)

Comments