javascript - Execution time for successful search Binary Search algorithm -


i have implemented binary search algorithm using node.js. recording time taken algorithm search number in random generated array. able output time taken algorithm unsuccessful search.

but not able figure out how measure time taken algorithm successfully search number in array.

here 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 = [];    (var = 0; < size; i++)    {        var temp = math.floor(math.random() * maxarrayvalue);        array.push(temp);    }    return array; }  var sortnumber = function(a, b) {    return - b; }  var program = function() {     (var = 0; <= 10000; += 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 using var time = process.hrtime(); start timer @ beginning of algorithm , using time = process.hrtime(time); end timer , output in console.

how can measure time taken algorithm successfully search number in array.

any appreciated.

start timer before calling binary search function , end after call .. regardless of whether search successful or not, time ..

var time = process.hrtime(); var result = binarysearch(sort, randomkey); time = process.hrtime(time); ...... 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -