ADS Unit 3 Notes
ADS Unit 3 Notes
Definition of an Array
An array is a data structure that stores a collection of elements of the same data type in a contiguous
block of memory. Each element in an array is accessed using an index, typically starting from zero.
1. Efficient Storage – Arrays allow storing multiple elements in a single variable, reducing memory
overhead.
2. Fast Access – Elements can be accessed in constant time O(1) using their index.
3. Easy Iteration – Arrays support looping structures (e.g., `for`, `while`) to process data efficiently.
4. Sorting and Searching – Many algorithms like binary search, bubble sort, and quicksort work
effectively with arrays.
5. Fixed Size (in some languages) – In languages like C and Java, arrays have a fixed size, making
memory management predictable.
6. Multidimensional Arrays – Useful for representing matrices, grids, and tables (e.g., a 2D array for
image processing).
7. Better Cache Performance – Since elements are stored contiguously in memory, accessing them
is faster due to improved cache locality.
Arrays can be classified based on their structure and usage. Here are two common types:
A one-dimensional array is a linear collection of elements stored in a single row or column. Each
element is accessed using a single index.
Example in C:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/27
2. Multi-Dimensional Array (2D or 3D Arrays)
A multi-dimensional array consists of multiple rows and columns, similar to a matrix. The most common
type is a two-dimensional (2D) array.
python
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2]) # Output: 6
Would you like me to explain other types, like dynamic or jagged arrays? 😊
In Python, arrays and lists are both used to store multiple values, but they have key differences in terms
of functionality, flexibility, and performance.
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/27
python
import array
python
import numpy as np
Key Takeaways
Use lists when you need flexibility (heterogeneous data, general-purpose storage).
Use arrays (`array` or `numpy`) for numerical operations requiring high performance and
memory efficiency.
Would you like a comparison on when to use NumPy over lists in data science? 🚀
python
# Step 2: Insertion
arr.append(60) # Append at the end
arr.insert(2, 25) # Insert 25 at index 2
print("After Insertion:", arr)
# Step 3: Deletion
arr.remove(30) # Remove the first occurrence of 30
deleted_element = arr.pop(3) # Remove element at index 3
print("After Deletion:", arr)
print(f"Deleted Element: {deleted_element}")
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/27
# Step 4: Traversal
print("Traversing the Array:")
for i in arr:
print(i, end=" ")
Output
sql
Explanation
Linear Search is a simple searching algorithm that checks each element in a list or array sequentially
until it finds the target value or reaches the end of the collection.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/27
python
# Example usage
numbers = [10, 25, 30, 45, 50]
key = 30
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
Time Complexity
Binary Search is an efficient searching algorithm that works on a sorted array by repeatedly dividing
the search interval in half. Instead of checking each element sequentially (like linear search), it
eliminates half of the remaining elements in each step.
python
if arr[mid] == target:
return mid # Element found
else:
high = mid - 1 # Search left half
# Example usage
numbers = [10, 20, 30, 40, 50] # Must be sorted
key = 30
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/27
Feature Linear Search Binary Search
Searches sequentially from the Searches by repeatedly dividing the array
Working Mechanism
beginning to the end. into halves.
Requirement Works on unsorted or sorted data. Works only on sorted data.
Time Complexity (Worst O(n) (If the element is at the last index O(log n) (Halves the search space in each
Case) or absent). step).
Speed Slower for large datasets. Much faster for large datasets.
Best Use Case When data is small or unsorted. When data is large and sorted.
Linear Search → When searching in an unsorted array or small data (e.g., searching for a name in
a list of random contacts).
Binary Search → When searching in a sorted array (e.g., looking up a word in a dictionary or
searching for a name in a sorted phonebook).
python
if arr[mid] == target:
return mid # Element found, return index
elif arr[mid] < target:
low = mid + 1 # Search right half
else:
high = mid - 1 # Search left half
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/27
return -1 # Element not found
if arr[mid] == target:
return mid # Element found
elif arr[mid] < target:
return binary_search_recursive(arr, mid + 1, high, target) # Search right half
else:
return binary_search_recursive(arr, low, mid - 1, target) # Search left half
# Example usage
sorted_array = [10, 20, 30, 40, 50, 60, 70] # Must be sorted
key = 40
How It Works
1. Iterative Approach:
Uses a `while` loop to repeatedly divide the array into halves.
Runs in O(log n) time complexity.
2. Recursive Approach:
Calls itself recursively on the left or right half until the element is found.
Also runs in O(log n) but has extra space usage due to recursion stack.
Example Output
pgsql
Would you like a step-by-step explanation of how binary search works with a specific example? 😊
Bubble Sort is a simple sorting algorithm that repeatedly compares adjacent elements and swaps
them if they are in the wrong order. This process continues until the entire list is sorted.
1. Start from the first element and compare it with the next element.
2. If the first element is greater, swap them.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/27
3. Move to the next pair and repeat the process.
4. After each full pass, the largest element "bubbles up" to its correct position.
5. Repeat the passes until no swaps are needed (i.e., the array is sorted).
python
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1): # Number of passes
swapped = False
for j in range(n - 1 - i): # Comparing adjacent elements
if arr[j] > arr[j + 1]: # Swap if needed
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped: # Optimization: Stop if no swaps were made
break
# Example usage
numbers = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(numbers)
print("Sorted Array:", numbers)
Explain the working of bubble sort with an example array. Analyze its
time complexity.
Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order.
This process continues until the entire array is sorted.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/27
Step-by-Step Execution:
Pass 3:
Pass 4:
Time
Case Explanation
Complexity
Best Case (Already Sorted) O(n) Optimized Bubble Sort stops early if no swaps are made.
Worst Case (Reversed Needs n-1 passes, with (n-1) + (n-2) + ... + 1 = O(n²)
O(n²)
Order) comparisons.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/27
Write a Python program to implement bubble sort and display the sorted
array.
5
Here is a Python program to implement Bubble Sort and display the sorted array:
python
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1): # Number of passes
swapped = False
for j in range(n - 1 - i): # Compare adjacent elements
if arr[j] > arr[j + 1]: # Swap if needed
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped: # Optimization: Stop if no swaps are made
break
# Example usage
numbers = [64, 34, 25, 12, 22, 11, 90] # Unsorted array
print("Original Array:", numbers)
Example Output
javascript
How It Works
Time Complexity
Selection Sort is a simple comparison-based sorting algorithm that divides the array into two parts:
It repeatedly selects the smallest element from the unsorted part and swaps it with the first
unsorted element, moving the boundary of the sorted section one step forward.
python
def selection_sort(arr):
n = len(arr)
for i in range(n - 1):
min_index = i # Assume first element is the smallest
for j in range(i + 1, n): # Find the smallest element in the remaining list
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i] # Swap with the first unsorted element
# Example usage
numbers = [64, 25, 12, 22, 11]
print("Original Array:", numbers)
Example Execution
1. Find the smallest (11) → Swap with `64` → `[11, 25, 12, 22, 64]`
2. Find the smallest (12) → Swap with `25` → `[11, 12, 25, 22, 64]`
3. Find the smallest (22) → Swap with `25` → `[11, 12, 22, 25, 64]`
4. Find the smallest (25) → Already in place.
5. Sorted Array: `[11, 12, 22, 25, 64]`
Describe the selection sort algorithm with an example array and explain
its time complexity
Selection Sort repeatedly finds the smallest element from the unsorted part of the array and swaps it
with the first unsorted element.
Step-by-Step Example
Sort the array [29, 10, 14, 37, 13] using Selection Sort
Initial Array:
Pass 1: (Find the smallest element and swap with the first element)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/27
Array after Pass 1: `[10, 29, 14, 37, 13]`
Pass 2: (Find the smallest in the remaining `[29, 14, 37, 13]`)
python
def selection_sort(arr):
n = len(arr)
for i in range(n - 1):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i] # Swap
# Example usage
numbers = [29, 10, 14, 37, 13]
print("Original Array:", numbers)
Time
Case Explanation
Complexity
Best Case (Already Sorted) O(n²) Always scans the unsorted part even if sorted.
Worst Case (Reversed
O(n²) Finds the minimum every time and swaps.
Order)
Always performs `(n-1) + (n-2) + ... + 1`
Average Case O(n²)
comparisons.
python
def selection_sort(arr):
n = len(arr)
for i in range(n - 1):
min_index = i # Assume the first element is the smallest
for j in range(i + 1, n): # Find the minimum element in the unsorted part
if arr[j] < arr[min_index]:
min_index = j # Update index of the minimum element
arr[i], arr[min_index] = arr[min_index], arr[i] # Swap with first unsorted element
# Example usage
numbers = [64, 25, 12, 22, 11] # Unsorted array
print("Original Array:", numbers)
Example Output
javascript
How It Works?
Time Complexity
What is a queue?
Definition of a Queue
A queue is a linear data structure that follows the FIFO (First In, First Out) principle. This means that
the element added first is the first one to be removed, just like a real-life queue (e.g., a line at a ticket
counter).
FIFO (First In, First Out): The first element inserted is the first one to be removed.
Enqueue (Insertion): Adding an element to the rear of the queue.
Dequeue (Deletion): Removing an element from the front of the queue.
Front and Rear:
Front: Points to the first element (to be dequeued).
Rear: Points to the last element (where new elements are enqueued).
python
# Create a queue
queue = deque()
Output:
less
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/27
Queue after dequeuing: [20, 30]
Would you like an explanation of types of queues (e.g., Circular Queue, Priority Queue)? 😊
Example:
Queue: Like a line at a ticket counter (first person in line is served first).
Stack: Like a stack of plates (last plate placed is the first one taken).
How It Works?
1. Enqueue (Insertion):
Create a new node.
If the queue is empty, both `front` and `rear` point to the new node.
Otherwise, update `rear.next` to the new node and move `rear` to it.
2. Dequeue (Deletion):
Remove the node at `front`.
Move `front` to the next node.
If `front` becomes `None`, set `rear = None` (queue is empty).
Diagram Representation
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/27
Before Any Operations (Empty Queue)
css
front → None
rear → None
css
css
python
# Node class
class Node:
def __init__(self, data):
self.data = data # Store the value
self.next = None # Pointer to the next node
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/27
# Example Usage
q = Queue()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
Example Output
rust
Here is a simple Queue implementation using a Python list, including enqueue (insertion), dequeue
(deletion), and display operations.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/27
python
class Queue:
def __init__(self):
self.queue = [] # Initialize an empty list as the queue
# Example Usage
q = Queue()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
q.dequeue()
q.dequeue()
q.dequeue() # Attempting to dequeue from an empty queue
Example Output
vbnet
Enqueued: 10
Enqueued: 20
Enqueued: 30
Queue: 10 -> 20 -> 30
Dequeued: 10
Queue: 20 -> 30
Dequeued: 20
Dequeued: 30
Queue is empty! Cannot dequeue.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/27
Operation Time Complexity
Enqueue (Insertion at rear) O(1)
🚀 Would you like an optimized version using for better performance (`O(1)`
dequeue time)? 😊
`collections.deque`
A priority queue is a special type of queue where each element has a priority. Elements are
dequeued based on priority rather than the order of insertion.
1. Each element has a priority (higher priority elements are dequeued first).
2. If two elements have the same priority, they follow FIFO (First In, First Out) order.
3. Implemented using a heap (binary heap) for efficient operations.
1. Max-Priority Queue → The highest priority element (largest value) is dequeued first.
2. Min-Priority Queue → The lowest priority element (smallest value) is dequeued first.
A patient with a heart attack (priority = 1) is treated before a patient with a fever (priority = 3).
If two patients have the same priority, the one who arrived first is treated first.
python
import heapq
class PriorityQueue:
def __init__(self):
self.queue = [] # Create an empty list
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/27
def dequeue(self):
if not self.is_empty():
priority, item = heapq.heappop(self.queue) # Removes the element with the lowest priori
print(f"Dequeued: {item} with priority {priority}")
return item
else:
print("Queue is empty! Cannot dequeue.")
return None
# Example Usage
pq = PriorityQueue()
pq.enqueue("Patient A", 2) # Lower priority number = higher importance
pq.enqueue("Patient B", 1) # Higher priority
pq.enqueue("Patient C", 3) # Lower priority
pq.display()
Example Output
vbnet
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/27
Feature Normal Queue Priority Queue
Ordering
FIFO (First In, First Out) Elements are dequeued based on priority
Principle
Insertion New elements are added at the rear New elements are added based on priority
Deletion Elements are removed from the front Highest priority element is removed first
Can be implemented using a list, linked Typically implemented using a heap (binary
Implementation
list, or deque heap) for efficiency
Used when order of arrival matters (e.g., Used when urgency matters (e.g., hospital
Use Case
ticket counters, call queues) emergency rooms, task scheduling)
Example Comparison
scss
scss
Key Takeaway
Use a Normal Queue when processing elements in strict arrival order (FIFO).
Use a Priority Queue when some elements need to be processed first based on urgency.
Priority queues are widely used in scenarios where tasks or elements must be processed based on
priority rather than arrival order. Below are some key real-life applications:
💻 Use Case: Operating systems use priority queues for process scheduling.
🔹 How It Works?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/27
Processes with higher priority (e.g., system tasks) are executed before lower-priority tasks.
The shortest job first (SJF) and priority scheduling algorithms use priority queues.
✅ Example:
A background download task (low priority) waits while a video call (high priority) gets CPU time first.
🛣️ Use Case: Used in Google Maps, GPS Navigation Systems, and Network Routing Protocols.
🔹 How It Works?
The algorithm selects the next closest node to visit based on distance.
A min-priority queue (min-heap) helps efficiently find the next node with the shortest path.
✅ Example:
Google Maps finds the shortest route by prioritizing roads with the lowest travel time.
🏥 Use Case: Hospitals use priority queues for patient treatment based on severity.
🔹 How It Works?
Patients with critical conditions (e.g., heart attacks) get treated first.
Less serious cases (e.g., common cold) wait longer.
✅ Example:
A heart attack patient (Priority = 1) is treated before a sprained ankle (Priority = 5).
✅ Example:
A one-page contract (Priority = High) prints before a 100-page document (Priority = Low).
🌐 Use Case: Routers and network switches prioritize high-importance data packets.
🔹 How It Works?
Video calls, live streams, and online gaming packets are prioritized over background downloads.
✅ Example:
A Zoom meeting packet (Priority = High) is transmitted before a file download packet (Priority =
Low).
✅ Example:
A self-driving car prioritizes avoiding obstacles over taking the shortest path.
📈 Use Case: Stock exchanges prioritize buy/sell orders based on price and urgency.
🔹 How It Works?
A buy order at a higher price is executed before lower-priced buy orders.
✅ Example:
A buy order at $150 (High Priority) is processed before a buy order at $140 (Low Priority).
✅ Example:
A business-class passenger (Priority = High) boards before an economy passenger (Priority = Low).
Conclusion
🔹 Priority queues help in real-life scenarios where tasks must be processed based on importance
rather than order.
🔹 They improve efficiency, reduce delays, and enhance user experience.
Would you like a Python example for any of these applications? 🚀😊
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 25/27
Python Code
python
class PriorityQueue:
def __init__(self):
self.queue = [] # Initialize an empty list as the priority queue
# Example Usage
pq = PriorityQueue()
pq.enqueue("Task A", 3) # Lower number = higher priority
pq.enqueue("Task B", 1) # Highest priority
pq.enqueue("Task C", 2)
pq.display()
Example Output
vbnet
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 26/27
Operation Time Complexity
Enqueue (Insertion + Sorting) O(n log n) (Sorting after each insert)
Dequeue (Removing first element) O(1)
Display (Traverse queue) O(n)
🔹 For better efficiency ( enqueue and dequeue), use a heap-based approach (`heapq`).
🚀😊
`O(log n)`
Would you like a heap-based priority queue implementation?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 27/27