Quickest Method To Find If A Number Exists In An Array Of Numbers
function xyz(arr, tar) {
len = arr.length;
if (len < 1) {
console.log("Not found.");
return
}
mid = Math.floor(len/2)
if (tar === arr[mid]) {
console.log("found", arr[mid]);
return
} else if (tar < arr[mid]) {
xyz(arr.slice(0, mid), tar);
} else if (tar > arr[mid]) {
xyz(arr.slice(mid+1), tar);
} else {
console.log("Not found");
}
}
array = [];
last = 0;
for (a = 0; a < 100; a++) {
array.push(Math.floor(Math.random() * 1000));
}
array.sort((a, b) => a - b);
tar = 500;
console.log(array);
console.time('function');
xyz(array, tar, array[0]);
console.timeEnd('function');
Run the above code here: https://repl.it/@VinitKhandelwal/quickest-find-element-in-array
Comments
Post a Comment