xsnippet logotype

xsnippet

binary_last_first [ JavaScript ]

by Guest
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const phoneBook = require('./phonebook.json');
const searchFor = { lastName: 'Rivera', firstName: 'Tabitha' };

function compare(value, searchValue) {
  if (value.lastName < searchValue.lastName) {
    return -1;
  } else if (value.lastName > searchValue.lastName) {
    return 1;
  } else {
    if (value.firstName < searchFor.firstName) {
      return -1;
    } else if (value.firstName > searchFor.firstName) {
      return 1;
    } else {
      return 0;
    }
  }
}

function binarySearch(array, value, comparator) {
  let start = 0;
  let end = array.length - 1;

  while (start <= end) {
    let mid = Math.floor((start + end)/ 2);
    let bingo = array[mid];
    const compareResult = comparator(bingo, value);

    if (compareResult === 0) {
      return bingo.phone;
    }

    if (compareResult === 1) {
      end = mid - 1;
    } else if (compareResult === -1) {
      start = mid + 1;
    }
  }

  return null;
}

function linearSearch(array, value, comparator) {
  for (let i = 0; i < array.length; i++) {
    const bingo = comparator(array[i], value);

    if (bingo === 0) {
      return array[i].phone;
    }
  }

  return null;
}

binarySearch(phoneBook, searchFor, compare);
linearSearch(phoneBook, searchFor, compare);

console.time('binarySearch');
const bBingo = binarySearch(phoneBook, searchFor, compare);
console.timeEnd('binarySearch');
console.log(bBingo);

console.time('linearSearch');
const lBingo = linearSearch(phoneBook, searchFor, compare);
console.timeEnd('linearSearch');
console.log(lBingo);