1 What Is an Algorithm?
An algorithm is a finite, unambiguous sequence of steps that solves a well-defined problem. Three properties are required: finiteness (it must terminate), definiteness (each step is precise), and effectiveness (each step is executable). The same problem may have many algorithms with very different costs.
- Input: zero or more values
- Output: one or more values related to the input
- Correctness: for every valid input the output satisfies the specification
Algorithm MAX(A, n):
max ← A[0]
for i ← 1 to n-1:
if A[i] > max: max ← A[i]
return max// Find the maximum element in an array
function arrayMax(arr) {
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
}
return max;
}
console.log(arrayMax([3, 1, 4, 1, 5, 9, 2, 6])); // 9