1. Home
  2. Explore
  3. Computer Science
  4. Week 3: Algorithms

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Week 3: Algorithms

  • 46Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Searching Algorithms

What is linear search? Provide a brief description.

46 questions

  1. 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. 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. 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. 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. 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. 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. 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. 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)O(n)O(n).

    Explanation

    In the worst case, the target is at the last position or absent, requiring checking all n elements.

  9. 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(log⁡n)O(\log n)O(logn).

    Explanation

    Each step halves the search space, so the number of steps is about log⁡2n\log_2 nlog2​n.

  10. 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. 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. 12

    What does Big Theta notation represent?

    Model answer

    Big Theta notation indicates that the algorithm's running time is both O(f(n))O(f(n))O(f(n)) and Ω(f(n))\Omega(f(n))Ω(f(n)), meaning the upper and lower bounds are the same.

    Explanation

    If an algorithm is Θ(n2)\Theta(n^2)Θ(n2), it always takes roughly n2n^2n2 steps regardless of input order.

  13. 13

    Give the Big O running time of linear search, binary search, selection sort, and merge sort.

    Model answer

    Linear search: O(n)O(n)O(n); binary search: O(log⁡n)O(\log n)O(logn); selection sort: O(n2)O(n^2)O(n2); merge sort: O(nlog⁡n)O(n \log n)O(nlogn).

    Explanation

    These are standard asymptotic bounds for these algorithms based on their operations.

  14. 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, 1000n1000n1000n and nnn are both O(n)O(n)O(n) because the linear term dominates any constant.

  15. 15

    What is the lower bound (Omega) of linear search? Why?

    Model answer

    The lower bound of linear search is Ω(1)\Omega(1)Ω(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. 16

    What is the lower bound (Omega) of selection sort? Why?

    Model answer

    The lower bound of selection sort is Ω(n2)\Omega(n^2)Ω(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. 17

    Under what condition can bubble sort achieve a lower bound of Ω(n)\Omega(n)Ω(n) instead of Ω(n2)\Omega(n^2)Ω(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)\Omega(n)Ω(n).

    Explanation

    If no swaps occur during one full pass, the array is sorted, and the algorithm can terminate after that pass.

  18. 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. 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)O(n^2)O(n2).

    Explanation

    It performs about n2/2n^2/2n2/2 comparisons regardless of input order.

  20. 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)\Omega(n^2)Ω(n2).

    Explanation

    Even when the array is already sorted, selection sort makes the same number of comparisons as in the worst case.

  21. 21

    Why is selection sort considered to be in Θ(n2)\Theta(n^2)Θ(n2)?

    Model answer

    Because its upper bound (O(n2)O(n^2)O(n2)) and lower bound (Ω(n2)\Omega(n^2)Ω(n2)) are the same, meaning it always takes about n2n^2n2 steps.

    Explanation

    The algorithm does not vary its number of comparisons based on input order.

  22. 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. 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)\Omega(n)Ω(n) when the input is already sorted.

  24. 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)O(n^2)O(n2).

    Explanation

    Each of n-1 passes makes up to n-1 comparisons, so total comparisons are about n2/2n^2/2n2/2.

  25. 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)\Omega(n)Ω(n).

    Explanation

    If the array is already sorted, only one pass is needed to confirm no swaps, requiring n-1 comparisons.

  26. 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. 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. 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. 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(nlog⁡n)O(n \log n)O(nlogn).

    Explanation

    The list is divided log⁡n\log nlogn times, and each level of merging takes O(n)O(n)O(n) steps, totaling O(nlog⁡n)O(n \log n)O(nlogn).

  30. 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 Ω(nlog⁡n)\Omega(n \log n)Ω(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 nlog⁡nn \log nnlogn without additional checks.

  31. 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)O(n)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. 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. 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. 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. 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. 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. 37

    How do you compare two strings in C? Why can't you use ==?

    Model answer

    Use the strcmp function from string.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. 38

    What does the strcmp function return when the two strings are equal?

    Model answer

    strcmp returns 0 when the two strings are equal.

    Explanation

    A return value of 0 indicates that the strings are identical character by character.

  39. 39

    What header file must be included to use strcmp?

    Model answer

    The string.h header file must be included.

    Explanation

    strcmp is declared in string.h along with other string utility functions.

  40. 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 person containing a name and a number field.

  41. 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].name accesses the name field of the first person in an array.

    Explanation

    The dot operator allows direct access to individual members of the structure.

  42. 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. 43

    How does using a structure like person improve 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. 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. 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 3 for 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. 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.

1 of 46
Question 1 of 46

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent