■ Algorithm (With Examples)
1. Definition
Algorithm ek finite sequence of well-defined steps hai jo ek problem ko systematically solve karta
hai. Simple words me: Algorithm = Recipe (cooking ki tarah step-by-step method).
2. Characteristics of a Good Algorithm (Properties)
• Input – 0 ya usse zyada inputs le. Example: 2 numbers input lena.
• Output – Kam se kam ek result de. Example: Sum of numbers.
• Definiteness – Har step clear ho. Example: Add a and b.
• Finiteness – Limited steps ke baad khatam ho. Example: Factorial algorithm.
• Effectiveness – Practical aur easy to follow ho. Example: Divide a chocolate.
• Generality – Multiple problems ke liye kaam kare. Example: Sorting algorithm.
3. Example Algorithm (Step-by-step)
Problem: 2 numbers ka sum nikalna
1 Start
2 Input two numbers a and b
3 Calculate sum = a + b
4 Print sum
5 Stop
■ Output: Agar input 5,7 diya to output = 12
4. Representation of Algorithm
Natural Language: 'Take two numbers, add them, print the result.'
Pseudocode:
START
INPUT a, b
sum ← a + b
PRINT sum
STOP
Flowchart (symbols: Oval=Start/Stop, Parallelogram=Input/Output, Rectangle=Process):
[Start] → [Input a,b] → [sum=a+b] → [Print sum] → [Stop]
5. Types of Algorithms with Examples
• Brute Force – Har possible option try karta hai. Example: Password crack.
• Divide and Conquer – Problem todkar solve karta hai. Example: Merge Sort (Divide →
Conquer → Combine).
• Greedy – Har step par best choice leta hai. Example: Coin Change Problem.
• Dynamic Programming – Results store aur reuse karta hai. Example: Fibonacci with DP.
• Backtracking – Galat hone par peeche jata hai. Example: N-Queens, Sudoku Solver.
• Recursive – Function khud ko call karta hai. Example: Factorial n = n * factorial(n-1).
6. Complexity of Algorithm
• Time Complexity – Execution time. Example: Linear Search O(n), Binary Search O(log n).
• Space Complexity – Memory usage. Example: DP zyada memory use karta hai.