简体   繁体   中英

how can i compare two arrays in Javascript by using binarysearch?

How can i use a binary search to compare two arrays and count the number of times it matched, i did find some here where one item was compared to an array..follwing is regular one for example ..thanx for the help.

var a = ["1", "2", "3", "4", "5", "6", "7"];
var b = ["8", "1", "3", "9", "4", "6", "8"];
var count = 0;

for (i = 0; i < a.length; i++) {
    for (j = 0; j < b.length; j++) {
        if (a[i] == b[j]) count += 1;
    }
}

document.write(count);

I tried to do this ..

for (i = 0; i < a.length; i++) {
    var left = 0;
    var right = b.length - 1;
    while (left <= right) {
        var mid = parseInt((left + right) / 2);
        if (b[mid] == a[i]) {
            count += 1;
        } else if (b[mid] < a[i]) {
            left = mid + 1;
        }
        else {
            right = mid - 1;
        }
    }
}

document.write(count);

Linearly go through the b array and use a binary search of the a array.

function binarySearch(a, value) {
    var left = 0;
    var right = a.length - 1;
    while (left <= right) {
        var mid = (left + right) >> 1;
        if (a[mid] === value) {
            return mid;
        } else if (a[mid] < value) {
            left = mid + 1;
        }
        else {
            right = mid - 1;
        }
    }
    return -1;
}


var a = ["1", "2", "3", "4", "5", "6", "7"];
var b = ["8", "1", "3", "9", "4", "6", "8"];
var count = 0;
b.forEach(function(value) { if (binarySearch(a, value) >= 0) ++count; });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM