0% found this document useful (0 votes)
6 views11 pages

Data Struc

The document outlines the differences between linear and non-linear collections, detailing data structures such as arrays and trees. It describes various algorithms including Bubble Sort, Binary Search, and Insertion Sort, along with their time complexities. Additionally, it covers stack operations, postfix evaluation, and the concepts of composition versus inheritance in programming.

Uploaded by

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

Data Struc

The document outlines the differences between linear and non-linear collections, detailing data structures such as arrays and trees. It describes various algorithms including Bubble Sort, Binary Search, and Insertion Sort, along with their time complexities. Additionally, it covers stack operations, postfix evaluation, and the concepts of composition versus inheritance in programming.

Uploaded by

lcott39
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Linear vs Non-Linear Collections:

1. Linear Collection:
a. A linear collection is a data structure that organizes elements sequentially,
where each element has a unique predecessor and a unique successor,
except for the first and last elements.
b. It represents a linear sequence of elements (e.g., arrays, linked lists).
2. Non-Linear Collection:
a. A non-linear collection does not organize elements sequentially.
b. Elements can have multiple predecessors or successors, forming complex
relationships (e.g., trees, graphs).

Algorithms and Their Descriptions:

Bubble Sort Algorithm:

• Purpose: Sort a list of elements in ascending order.


• Steps:
o Start with an unsorted list.
o Compare adjacent elements and swap them if they are out of order.
o Continue comparing and swapping until the largest unsorted element
bubbles to its correct position at the end.
o Repeat the process for remaining unsorted elements (n-1 passes for n
elements).
• Time Complexity: O(n²) for the worst and average case (quadratic time), making it
slower for large lists.

Binary Search Algorithm:

• Purpose: Find an element in a sorted collection.


• Steps:
o Start with a sorted collection and define the search space.
o Find the middle index of the search space:
mid=low+(high−low)/2\text{mid} = \text{low} + (\text{high} -
\text{low}) / 2mid=low+(high−low)/2.
o Compare the target element with the middle element:
▪ If equal, return the index.
▪ If less, reduce the search space to the lower half.
▪ If greater, reduce the search space to the upper half.
o Repeat until the target is found or the search space is empty.
• Time Complexity: O(log n) because the search space is halved each time.

Insertion Sort Algorithm:

• Purpose: Sort an array by building the sorted list one element at a time.
• Steps:
o Start with an unsorted array.
o Iterate through the array from the second element to the last.
o For each element, compare it with the sorted region (from right to left).
o Shift elements to the right until the correct position is found for the current
element.
o Insert the current element in its correct position in the sorted region.
• Time Complexity: O(n²) in the worst case, making it slower than more efficient
algorithms like quicksort.

Time Complexity Notations:

• Constant Time (O(1)): An operation that takes a fixed amount of time regardless of
the size of the input (e.g., accessing an element in an array).
• Logarithmic Time (O(log n)): An operation where the time grows logarithmically
with the input size (e.g., binary search).
• Linear Time (O(n)): An operation where the time grows linearly with the size of the
input (e.g., iterating through an array).
• Log-linear Time (O(n log n)): An operation that grows faster than linear but slower
than quadratic, like quicksort or mergesort.
• Quadratic Time (O(n²)): An operation where the time grows quadratically with the
input size (e.g., bubble sort, insertion sort).

Stack Operations:

1. Reversing a String Using a Stack:


a. Steps:
i. Create an empty stack.
ii. Push each character of the string onto the stack.
iii. Pop the characters from the stack one by one to form the reversed
string.
b. Time Complexity: O(n), where n is the length of the string.
2. Converting a Decimal Number to Binary Using a Stack:
a. Steps:
i. Create an empty stack.
ii. Repeatedly divide the decimal number by 2 and push the remainder
onto the stack.
iii. Once division is complete, pop the elements from the stack and
concatenate them to form the binary representation.
b. Time Complexity: O(log n), where n is the decimal number.
3. Checking for Balanced Brackets Using a Stack:
a. Steps:
i. Read the expression character by character.
ii. If an opening bracket is encountered, push it onto the stack.
iii. If a closing bracket is encountered, check if the stack is empty or if
the top element matches the opening bracket.
iv. If all brackets match and the stack is empty at the end, the expression
is balanced.
b. Time Complexity: O(n), where n is the length of the expression.

Postfix Evaluation:

• Steps:
o Create an empty stack for operands.
o Scan the expression from left to right:
▪ If the element is a number, push it onto the stack.
▪ If the element is an operator, pop the required operands, perform the
operation, and push the result back onto the stack.
o After processing all elements, the result will be in the stack.
• Time Complexity: O(n), where n is the number of elements in the expression.
Infix to Postfix Conversion:

• Steps:
o Scan the infix expression from left to right.
o If the element is an operand, append it directly to the postfix expression.
o If the element is an operator:
▪ Pop and append operators from the stack that have higher or equal
precedence.
▪ Push the current operator onto the stack.
o Handle parentheses:
▪ Push left parentheses onto the stack.
▪ Pop operators from the stack when encountering right parentheses
until the left parenthesis is encountered.
o After scanning the infix expression, pop all remaining operators from the
stack and append them to the postfix expression.
• Time Complexity: O(n), where n is the number of elements in the infix expression.

Composition vs Inheritance:

1. Benefits of Composition:
a. Code Reusability: By composing objects, you can reuse existing
functionality without inheriting unnecessary interfaces.
b. Modularity and Encapsulation: Composition allows functionality to be
divided into smaller, self-contained objects, leading to better separation of
concerns.
c. Flexibility and Extensibility: You can easily add or remove composed
objects to modify behavior without changing the containing class.
d. Simplified Interface: The containing class can expose a simplified interface,
hiding unnecessary details of the composed objects.
e. Reduced Coupling: Composition reduces dependency between classes
compared to inheritance, making the system more maintainable.

Linked List Operations:

• Insertion/Deletion at the Beginning: O(1) time complexity as it only involves


updating the head pointer.
• Insertion/Deletion at the End: O(n) time complexity, requiring traversal of the
entire list.
• Insertion/Deletion at a Specific Position: O(n) time complexity, as you need to
traverse the list to reach the desired position.

Software Engineering and Data Structures Practice Exam

Time Allowed: 1 Hour

Part 1: Multiple Choice Questions (MCQs)

(Each question is worth 2 points)

1. Which of the following is true about Non-Linear Collections? a) Elements are


accessed sequentially.

2. b) Elements have a single predecessor and successor.

3. c) Elements can have multiple predecessors and successors.

4. d) Elements can only be stored in arrays.

5. What is the time complexity of Bubble Sort in the best case (when the input
array is already sorted)? a) O(n)

b) O(log n)

c) O(n²)

d) O(1)

6. Which of the following operations is typically used in a Stack data structure? a)


enqueue

b) dequeue

c) push and pop


d) add and remove

7. In which scenario would you use a Non-Linear Collection like a tree or graph? a)
When you need to represent hierarchical data.

b) When you need to store a collection of elements in sequence.

c) When you need to quickly access elements by index.

d) When you need to perform quick lookups on unordered data.

8. Which algorithm has the time complexity O(n log n) in the average case? a)
Merge Sort

b) Bubble Sort

c) Quick Sort

d) Insertion Sort

9. What is the main advantage of using a stack for reversing a string? a) The
process is faster than using recursion.

b) It uses constant space.

c) The algorithm is simpler and easier to implement.

d) The algorithm runs in linear time (O(n)).

10. In a linked list, which of the following is the most efficient operation? a)
Searching for an element in the middle.

b) Inserting a node at the end of the list.

c) Inserting a node at the beginning of the list.

d) Deleting a node from the middle of the list.

11. What is the time complexity of performing a binary search on a sorted list of
size 'n'? a) O(n)

b) O(log n)
c) O(n²)

d) O(n log n)

12. Which of the following best describes Inheritance in object-oriented


programming? a) Creating a new class by combining behaviors of multiple classes.

b) A way to create a new class by extending an existing class.

c) A method of adding new methods to a class.

d) A technique to hide internal implementation details of a class.

13. What is the primary difference between a Queue and a Stack? a) A stack is a Last
In, First Out (LIFO) structure, while a queue is a First In, First Out (FIFO) structure.

b) A queue uses an array to store elements, while a stack uses a linked list.

c) A queue allows random access to elements, whereas a stack does not.

d) A stack allows insertion at both ends, whereas a queue only allows insertion at one end.

Part 2: Short Answer Questions

(Each question is worth 5 points)

1. Explain the concept of Composition in object-oriented programming. How is it


different from Inheritance?
a. Combining classes to create classes. Inheritance is a child of aparent
classe with many child that reuse similar feature
2. List the steps involved in performing a Binary Search on a sorted array. Also,
explain why the time complexity of Binary Search is O(log n).
3. Describe the difference between Linear and Non-Linear collections. Provide
one example of each and explain its typical use case.
4. What are the time complexities of the following algorithms in the worst case:
Bubble Sort, Insertion Sort, and Merge Sort? Compare their efficiency for large
datasets.
5. Explain how a stack is used in Postfix Evaluation. Provide an example to
illustrate the process of evaluating a Postfix expression using a stack.
Part 3: Coding Questions

(Each question is worth 10 points)

1. Write a C++ function to implement Insertion Sort. The function should take a
vector of integers and return the sorted vector.

#include <vector>
using namespace std;

vector<int> insertionSort(vector<int>& arr) {


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

2. Write a C++ function that checks whether a given string contains balanced
brackets (parentheses, square brackets, and curly braces) using a stack. The
function should return true if balanced, and false otherwise.

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

bool isBalancedBrackets(const string& expression) {


stack<char> s;
for (char c : expression) {
if (c == '(' || c == '{' || c == '[') {
s.push(c);
} else if (c == ')' && !s.empty() && s.top() == '(') {
s.pop();
} else if (c == '}' && !s.empty() && s.top() == '{') {
s.pop();
} else if (c == ']' && !s.empty() && s.top() == '[') {
s.pop();
} else {
return false;
}
}
return s.empty();
}

3. Write a C++ function to convert a decimal number to binary using a stack. The
function should return the binary representation as a string.

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

string decimalToBinary(int n) {
stack<int> s;
while (n > 0) {
s.push(n % 2);
n /= 2;
}
string result = "";
while (!s.empty()) {
result += to_string(s.top());
s.pop();
}
return result;
}

4. Write a C++ function that reverses a given string using a stack. The function
should return the reversed string.
#include <stack>
#include <string>
using namespace std;

string reverseString(const string& s) {


stack<char> sStack;
for (char c : s) {
sStack.push(c);
}
string reversed = "";
while (!sStack.empty()) {
reversed += sStack.top();
sStack.pop();
}
return reversed;
}

5. Write a C++ function to implement the Binary Search algorithm. The function
should take a sorted array and a target value as input, and return the index of
the target value or -1 if the target is not found.

#include <vector>
using namespace std;

int binarySearch(const vector<int>& arr, int target) {


int low = 0, high = arr.size() - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
Part 4: Long Answer Questions

(Each question is worth 15 points)

1. Explain the differences between Linear Collections (e.g., Arrays and Linked
Lists) and Non-Linear Collections (e.g., Trees and Graphs). Provide examples of
when to use each type of collection and the advantages they offer.
2. Discuss the importance of time complexity in algorithm analysis. Describe how
different time complexities (O(1), O(n), O(log n), O(n²), O(n log n)) affect the
performance of algorithms. Provide real-world examples for each time
complexity.
3. Explain the process of evaluating a Postfix expression using a stack. Discuss
the advantages of using a stack for postfix evaluation and provide an example
of how the stack is used to evaluate a postfix expression.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy