Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- worst case to find max in array:
- function max(array) {
- for (const itemA of array) {
- // Assume that it is the maximum value until we know otherwise
- let isMax = true;
- for (const itemB of array) {
- if (itemA < itemB) {
- // There is a value greater than itemA, so it is not the
- // maximum
- isMax = false;
- }
- }
- if (isMax) {
- return itemA;
- }
- }
- };
- next worst-
- function max(array) {
- for (const itemA of array) {
- // Assume that it is the maximum value until we know otherwise
- let isMax = true;
- for (const itemB of array) {
- if (itemA < itemB) {
- // There is a value greater than itemA, so it is not the
- // maximum
- isMax = false;
- // Don't keep checking the value
- break;
- }
- }
- if (isMax) {
- return itemA;
- }
- }
- };
- BEST CASE -
- function max(array) {
- if (array.length === 0) {
- return null;
- }
- let currentMax = array[0];
- for (let i=1; i<array.length; i++) {
- const item = array[i];
- if (item > currentMax) {
- currentMax = item;
- }
- }
- return currentMax;
- };
Add Comment
Please, Sign In to add comment