Linear time refers to an algorithms running time being proportional to the size of its inputs. As a result, if the input data size doubles, the algorithm will also double in running time.
Counting the instances of a particular element in an array can be viewed as an example of a linear time algorithm. Array elements are printed iteratively through the algorithm.
Printing given array values.
function printNumbers(arr) {
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
}
const arr = [10, 20, 30, 40, 50];
printNumbers(arr);
10
20
30
40
50
Printing Hello 'n' number of times.
function printHello(n) {
for (let i = 0; i < n; i++) {
console.log("Hello");
}
}
printHello(3);
Hello
Hello
Hello
Print Even or odd.
function printEven(arr) {
for (let i = 0; i < arr.length; i++) {
const res = arr[i] % 2 ? 'Odd' : 'Even'
console.log(res);
}
}
const arr = [10, 15, 20, 25];
printEven(arr);
Even
Odd
Even
Odd