Algorithm Fundamentals
Algorithm Fundamentals
It determines:
Examples:
Structure Description
Visual Example:
1|P age
2. Non-linear Data Structures
Elements are not in sequence; instead, they form a hierarchy or complex connections.
Examples:
Structure Description
Visual Example:
Tree:
2|P age
Graph:
Summary Table
3|P age
JavaScript Lists
1. List Representation
2. List Operations
4|P age
Operation Code Example Description
• Hold any type of data (numbers, strings, objects, even other arrays)
Index → 0 1 2 3 4
5|P age
Summary
Concept Example
Time Complexity
Time complexity is a measure of how fast an algorithm runs depending on the size of the input n.
Common Notations:
Space Complexity
Space complexity is a measure of how much memory an algorithm uses as the input size grows.
• Example:
6|P age
Classification of Sorting Algorithms
Sorting algorithms are ways to rearrange data into a desired order (usually ascending or descending).
Let’s classify them:
1. By Number of Comparisons
2. By Number of Swaps
3. By Memory Usage
4. By Recursion
5. By Stability
• Stable (preserves equal elements' order): Merge Sort, Insertion Sort, Bubble Sort
7|P age
6. By Adaptability
• Adaptive (faster for nearly-sorted data): Insertion Sort, Bubble Sort (with optimization)
7. Internal Sorting
8. External Sorting
Summary Table
Criteria Example
8|P age
Sorting Techniques
1️ Selection Sort
9|P age
• Idea: Repeatedly find the minimum element and move it to the front.
• Time: O(n²)
• In-place:
• Stable:
function selectionSort(arr) {
let min = i;
return arr;
2️ Bubble Sort
• Idea: Repeatedly swap adjacent elements if they are in the wrong order.
• Time: O(n²)
• In-place:
• Stable:
10 | P a g e
11 | P a g e
function bubbleSort(arr) {
let swapped;
do {
swapped = false;
swapped = true;
} while (swapped);
return arr;
12 | P a g e
3️ Insertion Sort
• Idea: Build the sorted array one element at a time.
• In-place:
• Stable:
function insertionSort(arr) {
arr[j + 1] = arr[j];
j--;
arr[j + 1] = key;
return arr; }
13 | P a g e
4️ Merge Sort
• Idea: Divide array into halves, sort each half, then merge them.
• Stable:
function mergeSort(arr) {
14 | P a g e
function merge(left, right) {
5️ Quick Sort
• Idea: Pick a pivot, partition array around it, and sort partitions.
• In-place:
• Stable:
15 | P a g e
function quickSort(arr) {
6️ Shell Sort
• Idea: Generalization of insertion sort, using gaps.
• In-place:
• Stable:
function shellSort(arr) {
let j = i;
j -= gap;
arr[j] = temp;
16 | P a g e
gap = Math.floor(gap / 2);
return arr;
7️ Heap Sort
• Idea: Convert to heap, then extract max/min repeatedly.
• In-place:
• Stable:
8️ Radix Sort
• Idea: Sort numbers by individual digits from least to most significant.
• In-place:
• Stable:
(Works only for integers, and best when digit count is small.)
9️ Counting Sort
• Idea: Count occurrences of each number and rebuild array.
• Time: O(n + k)
• In-place:
17 | P a g e
• Stable:
Bucket Sort
• Idea: Distribute elements into buckets, sort each, then merge.
• In-place:
• Stable:
Summary Table
18 | P a g e
Application of Linear Data Structures
1️ Linked List
Use Cases:
Basic Operations:
• Insert
• Delete
• Traverse
Procedure InsertAtBeginning(value)
Create new_node
new_node.data ← value
new_node.next ← head
head ← new_node
End Procedure
2️ Arrays
Use Cases:
• Lookup tables
19 | P a g e
Operations:
• Access
• Insert
• Delete
• Traverse
Procedure TraverseArray(arr, n)
For i ← 0 to n - 1
Print arr[i]
End For
End Procedure
3️ Queue (FIFO)
Use Cases:
• Job scheduling
• Printer queue
Operations:
• Enqueue
• Dequeue
• Peek
Procedure (Enqueue):
Procedure Enqueue(value)
20 | P a g e
Else
rear ← rear + 1
queue[rear] ← value
End If
End Procedure
4️ Stack (LIFO)
Use Cases:
• Undo mechanisms
Operations:
• Push
• Pop
• Peek
Procedure (Push):
Procedure Push(value)
Else
top ← top + 1
stack[top] ← value
End If
End Procedure
21 | P a g e
Application of Non-Linear Data Structures
1️ Tree
Use Cases:
• File systems
Operations:
• Insert
• Search
Procedure InOrder(node)
InOrder(node.left)
Print node.data
InOrder(node.right)
End If
End Procedure
2️ Graph
Use Cases:
• Social networks
• Network routing
22 | P a g e
Operations:
• Add vertex
• Add edge
• Search (DFS/BFS)
Procedure BFS(start_node)
Create queue
Enqueue start_node
current ← Dequeue
Enqueue neighbor
End If
End For
End While
End Procedure
Use Cases:
• Databases
• Caching
23 | P a g e
Operations:
• Insert
• Delete
• Search
index ← hash_function(key)
table[index] ← value
End Procedure
Summary Table
24 | P a g e
Learning outcome 3: Implement Algorithm using
JavaScript
Preparation of JavaScript Running Environment
To run JavaScript in the browser, you can follow these steps:
1. Browser Console: Open Chrome (or any modern browser), press F12 or Ctrl+Shift+I to open
Developer Tools, and go to the Console tab.
2. HTML + JS Files:
o Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Code</title>
</head>
<body>
</body>
</html>
25 | P a g e
3. Text Editor: Use editors like VS Code, Sublime Text, or Notepad++ to write your JavaScript.
1. Linked List
A Linked List is a collection of nodes, where each node has data and a reference to the next node.
class Node {
constructor(data) {
this.data = data;
this.next = null;
class LinkedList {
constructor() {
this.head = null;
insertAtBeginning(value) {
newNode.next = this.head;
this.head = newNode;
26 | P a g e
traverse() {
while (current) {
console.log(current.data);
current = current.next;
list.insertAtBeginning(10);
list.insertAtBeginning(20);
list.traverse(); // Output: 20 10
2. Arrays
JavaScript arrays are quite versatile, allowing you to store multiple types of data.
27 | P a g e
3. Queue
class Queue {
constructor() {
this.items = [];
enqueue(value) {
this.items.push(value);
dequeue() {
return this.items.shift();
peek() {
return this.items[0];
queue.enqueue(10);
queue.enqueue(20);
console.log(queue.dequeue()); // Output: 10
console.log(queue.peek()); // Output: 20
28 | P a g e
4. Stack
class Stack {
constructor() {
this.items = [];
push(value) {
this.items.push(value);
pop() {
return this.items.pop();
peek() {
stack.push(10);
stack.push(20);
console.log(stack.pop()); // Output: 20
console.log(stack.peek()); // Output: 10
29 | P a g e
5. Tree (Binary Search Tree)
A Binary Search Tree (BST) allows for fast searching, insertion, and deletion.
class TreeNode {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
class BinarySearchTree {
constructor() {
this.root = null;
insert(data) {
this.root = newNode;
return;
this.insertNode(this.root, newNode);
30 | P a g e
insertNode(node, newNode) {
} else {
traverseInOrder(node = this.root) {
this.traverseInOrder(node.left);
console.log(node.data);
this.traverseInOrder(node.right);
tree.insert(20);
tree.insert(10);
tree.insert(30);
tree.traverseInOrder(); // Output: 10 20 30
31 | P a g e
6. Graph
Graphs represent nodes and their connections (edges). Here's a basic implementation of an undirected
graph.
class Graph {
constructor() {
this.adjacencyList = {};
addVertex(vertex) {
if (!this.adjacencyList[vertex]) {
this.adjacencyList[vertex] = [];
addEdge(v1, v2) {
this.adjacencyList[v1].push(v2);
this.adjacencyList[v2].push(v1);
display() {
32 | P a g e
let graph = new Graph();
graph.addVertex("A");
graph.addVertex("B");
graph.addEdge("A", "B");
A Hash Table stores key-value pairs and uses a hash function for fast retrieval.
class HashTable {
constructor() {
hash(key) {
insert(key, value) {
this.table[index] = value;
get(key) {
return this.table[index];
33 | P a g e
let hashTable = new HashTable();
hashTable.insert(10, "Apple");
Sorting Operations
1. Bubble Sort
function bubbleSort(arr) {
let swapped;
do {
swapped = false;
swapped = true;
} while (swapped);
return arr;
34 | P a g e
2. Quick Sort
function quickSort(arr) {
Searching Operations
1. Binary Search
35 | P a g e
function binarySearch(arr, target) {
2. Linear Search
36 | P a g e
Running JavaScript Source Code
a. Rendering Engine
• A rendering engine is responsible for interpreting HTML, CSS, and JavaScript to display content
on the screen. Every browser has a rendering engine:
When you run JavaScript in a browser, the engine interprets and executes the JavaScript, dynamically
updating the DOM and CSS.
• Browser DevTools allow you to run JavaScript directly in the console, inspect elements, debug
code, and view performance metrics.
• Open DevTools and go to the Console tab to execute JavaScript directly. You can write code, call
functions, and view outputs in real time.
Example:
console.log("Hello, World!");
• In the Sources tab, you can debug JavaScript by setting breakpoints, stepping through the code,
and inspecting variables.
37 | P a g e
Using the Performance Tab:
• The Performance tab in DevTools allows you to measure the runtime of your JavaScript code.
You can record performance, capture the JavaScript execution timeline, and inspect memory
usage.
Most Integrated Development Environments (IDEs) like VS Code, WebStorm, or Sublime Text come with
terminal support to run JavaScript code.
1. Install Node.js: First, ensure you have Node.js installed, as it allows you to run JavaScript
outside the browser. You can download it here.
o Open the Terminal in VS Code (Ctrl+ or through the menu: Terminal -> New Terminal).
node filename.js
Example:
node script.js
• Time Complexity: Measures the number of operations (or steps) required for an algorithm to
complete as a function of its input size.
38 | P a g e
• Space Complexity: Measures the amount of memory used by an algorithm as a function of its
input size.
The goal is to assess whether the algorithm’s time and space usage grows efficiently as the input size
increases.
1. Profiling Tools
Profiling tools help track the time and space used by your JavaScript code and pinpoint performance
bottlenecks.
• In Chrome DevTools, you can use the Performance tab to record and analyze your JavaScript
code’s performance.
• You can start profiling by clicking the Record button and interacting with your app.
• The timeline will show where your JavaScript spends most of its time (e.g., rendering, layout,
script execution), helping you understand which parts of your code are taking the longest.
b. Node.js Profiler
2. Benchmarking Tools
a. Benchmark.js
Benchmark.js is a library for benchmarking JavaScript code performance. It helps compare different
pieces of code and measure their execution time.
39 | P a g e
Steps:
.on('cycle', function(event) {
console.log(String(event.target));
})
.run();
This will compare the performance of functionA and functionB and print the results.
b. Benchmarkify
Benchmarkify is another tool for benchmarking JavaScript functions. It’s more lightweight and easy to
integrate.
suite
.run();
40 | P a g e
c. jsPerf
jsPerf is an online tool for testing the performance of JavaScript code. You can create test cases for
different code snippets, share them, and see how they perform across different browsers.
• Go to jsPerf, write your test cases, and run them to compare performance across different
implementations.
You can measure the time complexity of a function directly in JavaScript using console.time and
console.timeEnd:
console.time('Sort Time');
This approach will give you the time it takes for the sorting operation to complete.
Summary of Tools
Profiling and performance Inspect and profile your JavaScript code in the
DevTools
measurement browser
Node.js
Profiling Node.js applications Profile server-side JavaScript code with --inspect
Profiler
Benchmarkify Lightweight benchmarking tool Quick benchmarking for small test cases
41 | P a g e
These tools and techniques will help you run JavaScript, measure its performance, and test algorithms
for time and space complexity efficiently.
THANK YOU!
42 | P a g e