Guest User

Untitled

a guest
Jun 18th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. worst case to find max in array:
  2. function max(array) {
  3. for (const itemA of array) {
  4. // Assume that it is the maximum value until we know otherwise
  5. let isMax = true;
  6.  
  7. for (const itemB of array) {
  8. if (itemA < itemB) {
  9. // There is a value greater than itemA, so it is not the
  10. // maximum
  11. isMax = false;
  12. }
  13. }
  14.  
  15. if (isMax) {
  16. return itemA;
  17. }
  18. }
  19. };
  20.  
  21. next worst-
  22.  
  23. function max(array) {
  24. for (const itemA of array) {
  25. // Assume that it is the maximum value until we know otherwise
  26. let isMax = true;
  27.  
  28. for (const itemB of array) {
  29. if (itemA < itemB) {
  30. // There is a value greater than itemA, so it is not the
  31. // maximum
  32. isMax = false;
  33. // Don't keep checking the value
  34. break;
  35. }
  36. }
  37.  
  38. if (isMax) {
  39. return itemA;
  40. }
  41. }
  42. };
  43. BEST CASE -
  44.  
  45. function max(array) {
  46. if (array.length === 0) {
  47. return null;
  48. }
  49.  
  50. let currentMax = array[0];
  51. for (let i=1; i<array.length; i++) {
  52. const item = array[i];
  53. if (item > currentMax) {
  54. currentMax = item;
  55. }
  56. }
  57. return currentMax;
  58. };
Add Comment
Please, Sign In to add comment