I have prepared 2 Javascript functions to find matching integer pairs that add up to a sum and returns a boolean.
The first function uses a binary search like that:
function find2PairsBySumLog(arr, sum) {
for (var i = 0; i < arr.length; i++) {
for (var x = i + 1; x < arr.length; x++) {
if (arr[i] + arr[x] == sum) {
return true;
}
}
}
return false;
}
For the second function I implemented my own singly LinkedList, in where I add the complementary integer to the sum and search for the value in the LinkedList. If value is found in the LinkedList we know there is a match.
function find2PairsBySumLin(arr, sum) {
var complementList = new LinkedList();
for (var i = 0; i < arr.length; i++) {
if (complementList.find(arr[i])) {
return true;
} else {
complementList.add(sum - arr[i]);
}
}
return false;
}
When I run both functions I clearly see that the second function executes ~75% faster
var arr = [1,2,4,1,3,2,9,8,1,9,10,1,2,8,9,8,2,4];
console.time('Binary');
console.log(find2PairsBySumLog(arr, 8));
console.timeEnd(‘Binary’);
console.time('Linear');
console.log(find2PairsBySumLin(arr, 8));
console.timeEnd('Linear');
true
Binary: 4.590ms
true
Linear: 0.709ms
Here my question: Is the LinkedList approach a real linear search? After all I loop through all the nodes, while my outer loop iterates through the initial array.
Here is my LinkedList search function:
LinkedList.prototype.find = function(data) {
var headNode = this.head;
if(headNode === null) {
return new Node(null);
}
while(headNode !== null) {
if(headNode.data === data) {
return true;
} else {
headNode = headNode.next;
}
}
return false;
}