๐ What is an Algorithm?
Algorithm:
An algorithm is a finite sequence of
well-defined steps used to solve a
problem or perform a specific task.
An algorithm normally contains: Input โ Processing โ Decision โ Output
๐ General Steps of an Algorithm
- Understand and define the problem.
- Identify the required input.
- Determine the expected output.
- Develop logical steps to solve the problem.
- Test the algorithm with sample data.
- Check the result and improve the solution.
๐ก Example: Find the Largest Number
Suppose we have the following numbers:
25, 12, 45, 8, 63, 31
We want the computer to determine which number is the largest.
Expected Output: 63
โ๏ธ Algorithm Steps
- Start.
- Read the array of numbers.
- Assume the first number is the largest.
- Read the next number.
- Compare it with the current largest number.
- If it is greater, update the largest number.
- Continue until all numbers are checked.
- Display the largest number.
- Stop.
๐งช Interactive Algorithm Engine
Enter numbers below and watch the internal processing mechanism.
COMPUTER PROCESSING ENGINE
READY
INPUT MEMORY
โ
Current number being read
from the array.
INDEX
โ
TOTAL
โ
PROCESSOR / CPU
WAITING
FOR INPUT
FOR INPUT
Comparison:
โ
No decision yet
WORKING MEMORY
โ
Current largest value stored
by the algorithm.
OLD
โ
NEW
โ
INPUT ARRAY / MEMORY CELLS
READ
โ
COMPARE
โ
DECIDE
โ
UPDATE
โ
NEXT
โ
OUTPUT
Press
Start Engine
to begin internal processing.
๐ What Happens Inside the Computer?
๐ฅ
1. READ
The CPU reads the next number
from input memory.
โ๏ธ
2. COMPARE
The CPU compares the current
number with the largest value.
๐ง
3. DECIDE
The processor decides whether
the largest value must change.
๐พ
4. UPDATE
If necessary, the new largest
value is stored in memory.
๐ฌ Internal Processing Example
INPUT MEMORY CPU PROCESSOR WORKING MEMORY
25 โ READ 25 โ โ
|
โ
INITIALIZE
|
โ
25
|
โ
STORE
|
โ
25
12 โ COMPARE โ 25
12 > 25 ?
|
โ
NO
|
โ
KEEP 25
45 โ COMPARE โ 25
45 > 25 ?
|
โ
YES
|
โ
UPDATE
|
โ
45
63 โ COMPARE โ 45
63 > 45 ?
|
โ
YES
|
โ
UPDATE
|
โ
63
FINAL OUTPUT
63
๐ Pseudocode
BEGIN
INPUT array
largest = first element
FOR each number in array
IF number > largest THEN
largest = number
END IF
END FOR
OUTPUT largest
END
๐ป JavaScript Implementation
function findLargest(numbers) {
let largest = numbers[0];
for (
let i = 1;
i < numbers.length;
i++
) {
if (numbers[i] > largest) {
largest = numbers[i];
}
}
return largest;
}
๐ Algorithm Complexity
Time Complexity
O(n)
Every number is checked once.
Space Complexity
O(1)
Only one main variable is required to store the largest value.