Guest User

Untitled

a guest
Jun 18th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. linear search -
  2.  
  3. function indexOf(array, value) {
  4. for (let i=0; i<array.length; i++) {
  5. if (array[i] == value) {
  6. return i;
  7. }
  8. }
  9. return -1;
  10. };
  11.  
  12. binary search -
  13.  
  14. function binarySearch(array, value, start, end) {
  15. var start = start === undefined ? 0 : start;
  16. var end = end === undefined ? array.length : end;
  17.  
  18. if (start > end) {
  19. return -1;
  20. }
  21.  
  22. const index = Math.floor((start + end) / 2);
  23. const item = array[index];
  24.  
  25. console.log(start, end);
  26. if (item == value) {
  27. return index;
  28. }
  29. else if (item < value) {
  30. return binarySearch(array, value, index + 1, end);
  31. }
  32. else if (item > value) {
  33. return binarySearch(array, value, start, index - 1);
  34. }
  35. };
  36.  
  37. Interview questions
  38. The share price for a company over a week's trading is as follows: [128, 97, 121, 123, 98, 97, 105]. If you had to buy shares in the company on one day, and sell the shares on one of the following days, write an algorithm to work out what the maximum profit you could make would be.
  39. Imagine that you wanted to find what the highest floor of a 100 story building you could drop an egg was, without the egg breaking. But you only have two eggs. Write an algorithm to work out which floors you should drop the eggs from to find this out in the most efficient way.
  40. Imagine you are looking for a book in a library with a Dewey Decimal index. How would you go about it? Can you express this process as a searching algorithm?
Add Comment
Please, Sign In to add comment