0% found this document useful (0 votes)
9 views10 pages

Data Structures: Sorting, Stacks, Queues

The document consists of lecture notes on Data Structures and Algorithms, covering sorting algorithms (Bubble Sort, Selection Sort, Insertion Sort) and data structures (Stacks and Queues). It includes definitions, importance, time complexities, basic and advanced C++ code implementations, and tasks for practice. Additionally, it provides references for further learning on each topic.

Uploaded by

22-05068
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views10 pages

Data Structures: Sorting, Stacks, Queues

The document consists of lecture notes on Data Structures and Algorithms, covering sorting algorithms (Bubble Sort, Selection Sort, Insertion Sort) and data structures (Stacks and Queues). It includes definitions, importance, time complexities, basic and advanced C++ code implementations, and tasks for practice. Additionally, it provides references for further learning on each topic.

Uploaded by

22-05068
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Lecture notes

Owner Assistant Professor POUL ISAAC C DE CHAVEZ

College College of Informatics and Computing Sciences

Subject Data Structure and Algorithm

Lecture #1: SORTING

● Definition:
Sorting is the process of arranging elements in a specific order, typically ascending
or descending.

● Why it's important:


- Easier to search data
- Necessary for binary search
- Prepares data for reporting or decision making

● Why Sorting Matters:


-Speeds up searching (e.g., binary search)
-Organizes data for human readability
-Enables efficient algorithms in databases and analytics
A. Bubble Sort
Time Complexity: O(n²)
● Simple sorting algorithm.
● Repeatedly compares adjacent elements and swaps them if they are in the wrong
order.

Bubble Sort

Basic C++ Code (Ascending Order):

#include <iostream>
using namespace std;

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1])
swap(arr[j], arr[j+1]);
}
}
}

int main() {
int arr[] = {5, 1, 4, 2};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}

Optimized Bubble Sort:

void optimizedBubbleSort(int arr[], int n) {


bool swapped;
for (int i = 0; i < n-1; i++) {
swapped = false;
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
swap(arr[j], arr[j+1]);
swapped = true;
}
}
if (!swapped) break;
}
}

B. Selection Sort
Time Complexity: O(n²)

● Repeatedly finds the minimum element and moves it to the front.

Selection Sort

Basic C++ Code:

void selectionSort(int arr[], int n) {


for (int i = 0; i < n-1; i++) {
int minIndex = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[minIndex])
minIndex = j;
swap(arr[i], arr[minIndex]);
}
}

Descending Order:

void selectionSortDescending(int arr[], int n) {


for (int i = 0; i < n-1; i++) {
int maxIndex = i;
for (int j = i+1; j < n; j++)
if (arr[j] > arr[maxIndex])
maxIndex = j;
swap(arr[i], arr[maxIndex]);
}
}

C. Insertion Sort
● Builds a sorted list one element at a time.
● Efficient for small datasets.

Insertion Sort
Basic C++ Code:

void insertionSort(int arr[], int n) {


for (int i = 1; i < n; i++) {
int key = arr[i], j = i-1;
while (j >= 0 && arr[j] > key)
arr[j+1] = arr[j--];
arr[j+1] = key;
}
}

With Insert Function:

void insert(int arr[], int n) {


int key = arr[n], j = n - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}

void insertionSort(int arr[], int n) {


for (int i = 1; i < n; i++)
insert(arr, i);
}

Lecture #2: STACKS


● Definition:
A stack is a linear data structure that follows the LIFO (Last-In, First-Out) principle.

LIFO (Last-In, First-Out)

Operations:

● Push(item): Add item on top

● Pop(): Remove item from top


● Peek(): View top item

● IsEmpty(): Check if empty

Basic C++ Code Using Array

#include <iostream>
using namespace std;

#define SIZE 5
int stack[SIZE], top = -1;

void push(int x) {
if (top < SIZE - 1)
stack[++top] = x;8
}

int pop() {
if (top >= 0)
return stack[top--];
return -1;
}

int main() {
push(10); push(20);
cout << "Popped: " << pop();
}

Advanced C++ Code Using STL

#include <iostream>
#include <stack>
using namespace std;

int main() {
stack<int> s;
[Link](5);
[Link](10);
[Link]();
cout << "Top: " << [Link]();
}
Lecture #3: QUEUES
● Definition:
A queue is a linear data structure that follows the FIFO (First-In, First-Out)
principle.

FIFO (First-In, First-Out)

Operations:

● Enqueue(item): Add to rear


● Dequeue(): Remove from front
● Front(): Peek first item
● IsEmpty()

Basic C++ Code Using Array

#define SIZE 5
int queue[SIZE], front = 0, rear = -1;

void enqueue(int x) {
if (rear < SIZE - 1)
queue[++rear] = x;
}

int dequeue() {
if (front <= rear)
return queue[front++];
return -1;
}

int main() {
enqueue(3); enqueue(5);
cout << "Dequeued: " << dequeue();
}

Advanced C++ Code Using STL


#include <iostream>
#include <queue>
using namespace std;

int main() {
queue<int> q;
[Link](1);
[Link](2);
[Link]();
cout << "Front: " << [Link]();
}

TASK 1: Activities with Answers (SHOW SOLUTION)


1. Trace Bubble Sort on [6, 3, 2]:
Answer: Pass 1: [3, 2, 6], Pass 2: [2, 3, 6]

2. Simulate Stack - Push(4), Push(6), Pop(), Push(2)


Answer: Stack from top: [2, 4]

3. Simulate Queue - Enqueue(7), Enqueue(9), Dequeue(), Enqueue(5)


Answer: Queue from front: [9, 5]

TASK 2: Short Answers


1. What principle does a stack follow?
Answer:

2. What does a queue use to manage order?


Answer:

3. Which sort algorithm swaps adjacent elements repeatedly?


Answer:

4. What is the result of popping an empty stack?


Answer:

5. What C++ STL class is used for stack implementation?


Answer:

TASK 3: Multiple Choice (Choose the correct answer):


1. Which of the following is a characteristic of stacks?

a. FIFO

b. LIFO

c. Random

d. None of the above

2. What is the main principle of a queue?

a. LIFO

b. Random

c. FIFO

d. FILO

3. Which sorting algorithm finds the smallest value and places it at the beginning?

a. Insertion Sort

b. Bubble Sort

c. Selection Sort

d. Merge Sort

4. What is the result of popping from an empty stack?

a. Adds an item

b. Views top item

c. Error or underflow

d. Removes bottom item

5. Which structure is best for a printer task queue?

a. Stack

b. Heap

c. Queue
d. Linked List

References:

A. Sorting Algorithms
1. Bubble Sort

● Learn Bubble Sort in 7 minutes


This tutorial offers a concise explanation of the Bubble Sort algorithm with
practical examples.
Watch on YouTubeYouTube+2YouTube+2YouTube+2

● Bubble Sort Algorithm using C++


A step-by-step guide to implementing Bubble Sort in C++, including code
walkthroughs.
Watch on YouTube

2. Selection Sort

● Selection Sort in 3 minutes


A quick overview of the Selection Sort algorithm, ideal for rapid revision.
Watch on YouTube

● Selection Sort | C++ Example


Demonstrates how to implement Selection Sort in C++ with clear code examples.
Watch on YouTube

3. Insertion Sort

● Learn Insertion Sort in 7 minutes


An easy-to-follow tutorial explaining the Insertion Sort algorithm with examples.
Watch on YouTubeYouTube

● Insertion Sort | C++ Example


Provides a detailed C++ implementation of Insertion Sort, suitable for beginners.
Watch on YouTube

B. Stack Data Structure


● What is STACK data structure in C++?
Explains the concept of stacks in C++ and how to work with them using STL.
Watch on YouTubeYouTube+6YouTube+6YouTube+6

● What is STACK data structure in C++? Stack in C++ STL with Example
A practical guide to implementing stacks in C++ using the Standard Template
Library.
Watch on YouTube

C. Queue Data Structure


● Queue Data Structure In STL | C++ Tutorial
Learn how to use the queue data structure built into the C++ Standard Template
Library.
Watch on YouTubeYouTube

● How to Use C++ STL Queue with an Example Program


A tutorial on implementing queues in C++ using STL, complete with example
programs.
Watch on YouTube

Common questions

Powered by AI

The use of STL in C++ facilitates the implementation of complex data structures like stacks and queues by providing pre-defined classes and functions that abstract the underlying complexity of these structures. STL's stack and queue classes manage the elements and their operations internally, which includes efficient handling of dynamic memory and ensuring performance optimization. This abstraction allows developers to focus on the application logic rather than implementation details, thus promoting modularity, reusability, and adherence to programming best practices .

Using the C++ Standard Template Library (STL) to implement stack and queue data structures offers several practical advantages over raw arrays. The STL provides robust, tested, and optimized implementations that handle dynamic memory management automatically, reducing the complexity and potential errors related to manual memory handling in raw arrays. STL also provides a more intuitive and flexible interface for accessing and managing elements, allowing for easier integration and modification. Furthermore, the STL implementations inherit the efficiency and reliability benefits of being part of the standard library, enhancing performance in real-world applications .

Queues are preferable for handling tasks in system processes like print jobs due to their FIFO (First-In, First-Out) nature which aligns with the order in which tasks are typically processed. This principle ensures that tasks are executed in the sequence they are received, maintaining a fair and predictable process flow that is essential for task scheduling and managing resource allocation in system environments. The ability to dequeue the oldest request first allows for orderly and timely handling of operations .

The LIFO (Last-In, First-Out) principle in stacks allows the last added element to be the first one removed. In contrast, the FIFO (First-In, First-Out) principle in queues processes elements in the order they were added, meaning the first element added is the first one removed. This distinction impacts their use cases: stacks are ideal for tasks that require reverse sequential processing, such as evaluating expressions or managing function calls, while queues are suited for ordered processing tasks, like scheduling and managing task queues in systems .

Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order, until the entire list is sorted. It has a time complexity of O(n²) and is generally less efficient on average compared to other algorithms . Selection Sort, on the other hand, repeatedly selects the minimum (or maximum) element from the unsorted portion and moves it to the beginning (or end) of the sorted portion. It also has a time complexity of O(n²) but typically performs fewer swaps than Bubble Sort, potentially offering better performance in some cases .

The early termination feature in optimized Bubble Sort markedly improves its practical performance by reducing the number of unnecessary iterations through the dataset. This optimization becomes especially beneficial when the array is already sorted or requires minimal swaps, leading to best-case time complexities approaching O(n) rather than O(n²). This feature can significantly enhance efficiency in real-world scenarios where datasets are often nearly sorted due to prior operations, making optimized Bubble Sort competitive with more complex algorithms under such conditions .

Selection Sort might be less preferred for large datasets because, despite its predictable swap count, it still has a time complexity of O(n²), which results in inefficient performance for large inputs. The algorithm's approach of scanning the unsorted portion to find the minimum element incurs the same quadratic number of comparisons as Bubble Sort, leading to slow execution as the dataset size increases. This inefficiency outweighs the benefit of reduced swaps, making Selection Sort unsuitable for large datasets .

The 'swapped' variable in the optimized Bubble Sort algorithm is used to track whether any elements were swapped during a pass through the array. If no elements are swapped, it indicates that the array is already sorted, allowing the algorithm to terminate early, which reduces the number of unnecessary passes. This optimization can significantly improve the performance of Bubble Sort by avoiding redundant comparisons if the list becomes fully sorted before completing all possible iterations .

Insertion Sort would be preferred in situations where the dataset is relatively small or partially sorted, as it has an adaptive time complexity that performs well in these scenarios. It builds the sorted array one element at a time and can be very efficient with a time complexity closer to O(n) in the best case where the array is already substantially sorted. This makes it a good choice for small arrays, where the overhead of more complex sorting algorithms would be inefficient .

Sorting is essential for enhancing data search efficiency because it organizes data in a way that allows for more efficient search algorithms like binary search. Binary search requires that the data be in a sorted order because it works by repeatedly dividing the search interval in half, which is only possible when elements are in a sequential order. This reduces the time complexity significantly from O(n) in linear search to O(log n) in binary search, making sorted data crucial for efficient search operations .

You might also like