Week 3: Algorithms
- 46Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is linear search? Provide a brief description.
46 questions
- 1
What is linear search? Provide a brief description.
Model answer
Linear search is an algorithm that checks each element of a list sequentially from left to right until the target value is found or the list ends.
Explanation
Linear search is the simplest searching algorithm; it works on unsorted data and has a worst-case time complexity of O(n).
- 2
Why is it incorrect to return false inside the loop in linear search after checking one element?
Model answer
Returning false inside the loop would incorrectly conclude that the target is absent after only checking the first element, ignoring the rest of the list.
Explanation
The correct approach is to return false only after the loop completes, meaning all elements have been checked without finding the target.
- 3
Write pseudocode for linear search that correctly handles finding or not finding an element.
Model answer
For each door from left to right: if 50 is behind door, return true; after loop, return false.
Explanation
The pseudocode ensures that 'return false' occurs only after all doors have been examined without success.
- 4
What is binary search? Under what condition can binary search be used?
Model answer
Binary search is an algorithm that repeatedly divides a sorted list in half, comparing the target to the middle element. It requires the data to be sorted.
Explanation
Without sorted data, binary search cannot make logical decisions to go left or right based on comparisons.
- 5
Write pseudocode for binary search, including the base case when no doors are left.
Model answer
If no doors left, return false; if 50 is behind middle door, return true; else if 50 < middle, search left half; else if 50 > middle, search right half.
Explanation
The base case handles the scenario where the element is not present, ensuring termination.
- 6
Why does binary search require sorted data?
Model answer
Binary search relies on the ordering of data to decide which half to search next; without sorted data, the comparison to the middle element gives no information about the location of the target.
Explanation
If data is unsorted, knowing that the middle element is 20 does not indicate whether 50 is to the left or right.
- 7
In an array of n elements, what are the indices of the first and last elements?
Model answer
The first element is at index 0, and the last element is at index n-1.
Explanation
C arrays are zero-indexed, so the last index is always one less than the number of elements.
- 8
How many steps does linear search take in the worst case? Express in Big O notation.
Model answer
Linear search has a worst-case running time of O(n).
Explanation
In the worst case, the target is at the last position or absent, requiring checking all n elements.
- 9
How many steps does binary search take in the worst case? Express in Big O notation.
Model answer
Binary search has a worst-case running time of O(logn).
Explanation
Each step halves the search space, so the number of steps is about log2n.
- 10
What does Big O notation represent in algorithm analysis?
Model answer
Big O notation represents an upper bound on the running time of an algorithm, describing the worst-case number of steps as the input size grows.
Explanation
It focuses on the dominant term and ignores constant factors, allowing comparison of algorithms' scalability.
- 11
What does Big Omega notation represent?
Model answer
Big Omega notation represents a lower bound on the running time of an algorithm, describing the best-case number of steps.
Explanation
It gives the minimum number of steps an algorithm will take for some input of size n.
- 12
What does Big Theta notation represent?
Model answer
Big Theta notation indicates that the algorithm's running time is both O(f(n)) and Ω(f(n)), meaning the upper and lower bounds are the same.
Explanation
If an algorithm is Θ(n2), it always takes roughly n2 steps regardless of input order.
- 13
Give the Big O running time of linear search, binary search, selection sort, and merge sort.
Model answer
Linear search: O(n); binary search: O(logn); selection sort: O(n2); merge sort: O(nlogn).
Explanation
These are standard asymptotic bounds for these algorithms based on their operations.
- 14
Why does asymptotic notation ignore constant factors and lower-order terms?
Model answer
As n grows large, constant factors and lower-order terms become insignificant compared to the highest-order term, so they do not affect the algorithm's scalability.
Explanation
For example, 1000n and n are both O(n) because the linear term dominates any constant.
- 15
What is the lower bound (Omega) of linear search? Why?
Model answer
The lower bound of linear search is Ω(1), because in the best case the target is at the first position.
Explanation
If the target is found immediately, only one comparison is needed.
- 16
What is the lower bound (Omega) of selection sort? Why?
Model answer
The lower bound of selection sort is Ω(n2) because even if the array is already sorted, the algorithm still performs all comparisons as specified in its pseudocode.
Explanation
Selection sort always scans the entire unsorted portion to find the minimum, regardless of input order.
- 17
Under what condition can bubble sort achieve a lower bound of Ω(n) instead of Ω(n2)?
Model answer
If bubble sort is optimized with a check for whether any swaps were made on a pass, it can stop early when the array is already sorted, achieving Ω(n).
Explanation
If no swaps occur during one full pass, the array is sorted, and the algorithm can terminate after that pass.
- 18
Describe the selection sort algorithm step by step.
Model answer
For each position i from 0 to n-1: find the smallest element in the unsorted portion (i to n-1), then swap it with the element at position i.
Explanation
This repeatedly selects the minimum and places it in its correct position, gradually building a sorted list from left to right.
- 19
What is the worst-case running time of selection sort? Express in Big O notation.
Model answer
Selection sort has a worst-case running time of O(n2).
Explanation
It performs about n2/2 comparisons regardless of input order.
- 20
What is the best-case running time of selection sort? Express in Big Omega notation.
Model answer
The best-case running time of selection sort is Ω(n2).
Explanation
Even when the array is already sorted, selection sort makes the same number of comparisons as in the worst case.
- 21
Why is selection sort considered to be in Θ(n2)?
Model answer
Because its upper bound (O(n2)) and lower bound (Ω(n2)) are the same, meaning it always takes about n2 steps.
Explanation
The algorithm does not vary its number of comparisons based on input order.
- 22
Describe the bubble sort algorithm step by step.
Model answer
Repeat n-1 times: for each i from 0 to n-2, compare elements at i and i+1; if out of order, swap them. Larger elements bubble to the end.
Explanation
Each pass places the next largest element in its correct position at the end of the array.
- 23
How can bubble sort be optimized to stop early if the array is already sorted?
Model answer
After each full pass, check if any swaps were made; if no swaps occurred, the array is sorted and the algorithm can terminate early.
Explanation
This optimization reduces the best-case running time to Ω(n) when the input is already sorted.
- 24
What is the worst-case running time of bubble sort? Express in Big O notation.
Model answer
Bubble sort has a worst-case running time of O(n2).
Explanation
Each of n-1 passes makes up to n-1 comparisons, so total comparisons are about n2/2.
- 25
With the optimization, what is the best-case running time of bubble sort? Express in Big Omega notation.
Model answer
With the swap-check optimization, bubble sort's best-case running time is Ω(n).
Explanation
If the array is already sorted, only one pass is needed to confirm no swaps, requiring n-1 comparisons.
- 26
Why might a programmer choose to implement a simpler algorithm like bubble sort instead of a more efficient one?
Model answer
Bubble sort is easy to implement and debug; for small data sets, the difference in efficiency may be negligible, and developer time is saved.
Explanation
Sometimes the simplicity of code outweighs performance gains, especially when n is small or when code readability is important.
- 27
Describe the merge sort algorithm in three steps.
Model answer
Step 1: Sort the left half of the list. Step 2: Sort the right half of the list. Step 3: Merge the two sorted halves into one sorted list.
Explanation
This recursive strategy divides the problem until single elements remain, then merges sorted sublists efficiently.
- 28
Explain how the merge step works when merging two sorted lists.
Model answer
Compare the first elements of each list; take the smaller element and place it in the output, then advance in that list. Repeat until both lists are exhausted.
Explanation
This process takes exactly n steps for two lists of total size n because each element is moved once.
- 29
What is the running time of merge sort in the worst case? Express in Big O notation.
Model answer
Merge sort has a worst-case running time of O(nlogn).
Explanation
The list is divided logn times, and each level of merging takes O(n) steps, totaling O(nlogn).
- 30
What is the running time of merge sort in the best case? Express in Big Omega notation.
Model answer
Merge sort has a best-case running time of Ω(nlogn).
Explanation
Even if the list is already sorted, merge sort still performs all divisions and merging as specified, so it does not achieve a lower bound better than nlogn without additional checks.
- 31
What is a trade-off associated with merge sort compared to selection sort?
Model answer
Merge sort requires extra memory space to store the merged lists (typically O(n) additional space), whereas selection sort sorts in place.
Explanation
The improved running time of merge sort comes at the cost of increased memory usage.
- 32
Define recursion in the context of programming.
Model answer
Recursion is a technique where a function calls itself to solve smaller instances of the same problem.
Explanation
Recursive functions typically have a base case to stop recursion and a recursive case that reduces the problem size.
- 33
What is a base case in a recursive function?
Model answer
A base case is a simple condition that stops the recursion by directly returning a result without further recursive calls.
Explanation
Without a base case, recursion would continue indefinitely, causing a stack overflow.
- 34
In the recursive pyramid example, what is the base case and what is the recursive case?
Model answer
Base case: if n equals 0, do nothing. Recursive case: draw a pyramid of height n-1, then print one row of n bricks.
Explanation
The base case terminates recursion when the height reaches zero; the recursive case builds the pyramid from the top down.
- 35
How does the recursive pyramid function work for height 4? Trace the calls.
Model answer
draw(4) calls draw(3) calls draw(2) calls draw(1) calls draw(0) which returns; then draw(1) prints 1 brick, draw(2) prints 2 bricks, draw(3) prints 3 bricks, draw(4) prints 4 bricks.
Explanation
The recursion first goes down to the base case, then unwinds printing rows from smallest to largest.
- 36
Why is recursion a suitable approach for merge sort?
Model answer
Merge sort naturally divides the problem into smaller subproblems (sorting halves) that are solved in the same way, making recursion a natural fit.
Explanation
Recursion allows expressing the divide-and-conquer strategy concisely: sort left, sort right, merge.
- 37
How do you compare two strings in C? Why can't you use ==?
Model answer
Use the
strcmpfunction fromstring.h. The == operator compares memory addresses, not the actual string contents.Explanation
Strings in C are arrays of characters, and == would check if both pointers point to the same location, not if the characters match.
- 38
What does the
strcmpfunction return when the two strings are equal?Model answer
strcmpreturns 0 when the two strings are equal.Explanation
A return value of 0 indicates that the strings are identical character by character.
- 39
What header file must be included to use
strcmp?Model answer
The
string.hheader file must be included.Explanation
strcmpis declared instring.halong with other string utility functions. - 40
How do you define a custom data type (structure) in C? Provide syntax.
Model answer
Use
typedef struct { field declarations } type_name;. Example:typedef struct { string name; string number; } person;Explanation
This creates a new type
personcontaining a name and a number field. - 41
How do you access a field of a structure using a variable?
Model answer
Use the dot operator:
variable.field. For example,people[0].nameaccesses the name field of the first person in an array.Explanation
The dot operator allows direct access to individual members of the structure.
- 42
What is a parallel array, and what is a disadvantage of using parallel arrays?
Model answer
Parallel arrays are separate arrays that store related data (e.g., names and numbers) with corresponding indices. A disadvantage is that maintaining alignment is error-prone.
Explanation
If elements are added or removed in one array, the other must be updated consistently, leading to bugs.
- 43
How does using a structure like
personimprove code design compared to parallel arrays?Model answer
A structure encapsulates related data into a single unit, ensuring that all fields for an item are always together, reducing the risk of misalignment.
Explanation
With a structure, each person object contains both name and number, so operations like sorting or searching affect both fields simultaneously.
- 44
Why should phone numbers be stored as strings rather than integers in most cases?
Model answer
Phone numbers often contain formatting characters like hyphens or parentheses, and no arithmetic is performed on them, so strings are more appropriate.
Explanation
Using integers would lose leading zeros and punctuation; strings preserve the intended format.
- 45
What is a magic number in programming, and why is it discouraged?
Model answer
A magic number is a hardcoded numeric literal in code, such as
3for an array size. It is discouraged because it makes code less readable and harder to maintain if the value changes.Explanation
Using named constants or calculating sizes dynamically improves code flexibility and reduces errors.
- 46
Why is it important to initialize arrays? What happens if you don't?
Model answer
Uninitialized arrays contain garbage values (remnants of previous memory usage), leading to unpredictable program behavior.
Explanation
Accessing uninitialized memory can cause incorrect results or crashes. Always initialize arrays with known values.

Ask anything
We've read this whole study set, so questions about it get the best answers.