1. Home
  2. Explore
  3. Computer Science
  4. Memory and Pointers

Study methods

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

Memory and Pointers

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

How does linear search find a target in an array, and what should it return if it reaches the end without finding the target?

55 questions

  1. 1

    How does linear search find a target in an array, and what should it return if it reaches the end without finding the target?

    Model answer

    It checks array elements one at a time, typically from left to right, and returns true when an element matches the target. If it checks every element without a match, it returns false.

    Explanation

    The search proceeds step by step through the array; reaching the end without a match means the target is absent.

  2. 2

    Why can linear search be the best available approach when an array is unsorted and its order is unknown?

    Model answer

    Without useful ordering information, the search may need to inspect every element to determine whether the target is present.

    Explanation

    In the worst case, the target is last or absent, so no unchecked element can safely be skipped.

  3. 3

    What condition must hold for binary search to be used correctly?

    Model answer

    The elements must be sorted in an order that lets the search determine which half could contain the target.

    Explanation

    Binary search uses comparisons with a middle element to discard one half of the search range.

  4. 4

    Describe the main steps of binary search.

    Model answer

    Check the middle element; if it matches, report success. Otherwise, search the half that could contain the target, repeating until the target is found or no elements remain.

    Explanation

    Each comparison either finds the target or eliminates one half of the remaining candidates.

  5. 5

    What are the worst-case running times of linear search and binary search in terms of the number of elements nnn?

    Model answer

    Linear search is O(n)O(n)O(n), while binary search is O(log⁡n)O(\log n)O(logn).

    Explanation

    Linear search may inspect all nnn elements; binary search repeatedly halves the search range.

  6. 6

    What are the best-case running times of linear search and binary search?

    Model answer

    Both can be Ω(1)\Omega(1)Ω(1) because the target may be found on the first comparison.

    Explanation

    For linear search, the target can be first; for binary search, it can be in the middle.

  7. 7

    Why is the cost of sorting relevant when deciding whether to use binary search instead of linear search?

    Model answer

    Binary search requires sorted data, so the time spent sorting must be weighed against the time saved by faster searches.

    Explanation

    Sorting may be worthwhile when the same data will be searched repeatedly, but not necessarily when searching only once.

  8. 8

    What does big O notation describe, and why is it commonly used for algorithm analysis?

    Model answer

    Big O describes an asymptotic upper bound on an algorithm’s running time. It gives a simplified way to characterize how the work grows as the input gets larger.

    Explanation

    It focuses on growth for large inputs rather than exact step counts.

  9. 9

    Why are constant factors and the base of a logarithm usually omitted in big O descriptions?

    Model answer

    For sufficiently large inputs, constant factors and different logarithm bases do not change the asymptotic growth class.

    Explanation

    Big O abstracts away multiplicative constants, so, for example, O(n/2)O(n/2)O(n/2) is written as O(n)O(n)O(n).

  10. 10

    What does omega notation describe, and how does it differ from big O notation?

    Model answer

    Omega notation describes an asymptotic lower bound, often used for an algorithm’s best-case running time; big O describes an upper bound, often used for its worst case.

    Explanation

    The two notations characterize different bounds on how much work an algorithm may require.

  11. 11

    Give an example of a task whose running time is both O(n)O(n)O(n) and Ω(n)\Omega(n)Ω(n), and explain why.

    Model answer

    Counting all elements in a collection takes O(n)O(n)O(n) and Ω(n)\Omega(n)Ω(n) because every element must be examined, even in the best case.

    Explanation

    The task requires inspecting all nnn items regardless of their arrangement.

  12. 12

    When can an algorithm be described using theta notation?

    Model answer

    When its asymptotic upper and lower bounds are the same, theta notation gives a matching bound on its growth.

    Explanation

    For example, an algorithm with both O(n2)O(n^2)O(n2) and Ω(n2)\Omega(n^2)Ω(n2) running times is Θ(n2)\Theta(n^2)Θ(n2).

  13. 13

    How can a C array be initialized with known values using shorthand notation?

    Model answer

    Use an initializer list in curly braces, such as int numbers[] = {4, 8, 15};.

    Explanation

    This statically initializes the array with the listed values and avoids assigning each element separately.

  14. 14

    How does a loop perform a linear search through a C array?

    Model answer

    It iterates over the valid indices, compares each element with the target, and reports a match when one is found; otherwise, it reports no match after the loop.

    Explanation

    For an array of nnn elements, valid indices run from 000 to n−1n-1n−1.

  15. 15

    Why can’t C compare two strings for equality using == in the same way it compares integers?

    Model answer

    A C string is a sequence of characters, not a simple scalar value, so string equality requires comparing the string contents rather than using ==.

    Explanation

    The content of strings may include multiple characters, which must be compared to establish equality.

  16. 16

    How does the C function strcmp indicate that two strings are equal?

    Model answer

    strcmp returns 000 when the strings are equal, a negative value when the first string comes earlier alphabetically, and a positive value when it comes later.

    Explanation

    For an equality test, check whether the result of strcmp is 000.

  17. 17

    Which header file is needed to use strcmp in C?

    Model answer

    Include string.h.

    Explanation

    The function’s declaration is provided by the string.h header.

  18. 18

    Why should a phone number generally be represented as a string rather than an integer?

    Model answer

    Phone numbers can contain formatting characters and leading zeros, which are not appropriately represented as numeric values.

    Explanation

    Dashes, parentheses, plus signs, and leading zeros may carry meaning or need to be preserved.

  19. 19

    What do return values of 000 and 111 conventionally signify when a C program exits?

    Model answer

    A return value of 000 conventionally indicates success, while a nonzero value such as 111 indicates failure.

    Explanation

    These are common conventions for communicating a program’s outcome to the operating environment.

  20. 20

    What is a C struct, and why is it useful?

    Model answer

    A struct is a container for multiple related data fields, potentially of different types. It lets a program keep information that belongs together in one record.

    Explanation

    For example, one structure can hold a person’s name and phone number together.

  21. 21

    What is the purpose of typedef when defining a custom structure type in C?

    Model answer

    typedef creates a type name that can be used to declare variables of the newly defined structure type.

    Explanation

    It allows a program to define and then use a custom type such as person.

  22. 22

    How do you access a field of a structure stored in an array in C?

    Model answer

    Use the array index followed by a dot and the field name, as in people[i].name.

    Explanation

    The index selects a structure in the array, and the dot selects one of its fields.

  23. 23

    What design risk arises when names and phone numbers are stored in separate arrays and associated only by matching indices?

    Model answer

    The arrays can become misaligned, causing a name to be associated with the wrong number.

    Explanation

    Keeping the two arrays in sync depends on an informal agreement that can be broken by edits or sorting.

  24. 24

    How does storing each person’s name and number in one structure improve the design of a phone book?

    Model answer

    It keeps related fields together, so reordering people does not separate a name from its corresponding number.

    Explanation

    Each array element represents a complete person record rather than one piece of information.

  25. 25

    What is bubble sort’s basic rule for rearranging a list?

    Model answer

    It repeatedly compares adjacent elements and swaps them when they are out of order.

    Explanation

    Repeated passes move larger elements toward their correct positions at the end of the list.

  26. 26

    Why is bubble sort called bubble sort?

    Model answer

    During repeated adjacent comparisons and swaps, larger elements move or “bubble” toward the end of the list.

    Explanation

    The name describes the visible movement of elements through successive passes.

  27. 27

    What is the worst-case running time of the basic bubble sort described in the content, and why?

    Model answer

    It is O(n2)O(n^2)O(n2) because it performs about nnn passes, with each pass comparing about nnn adjacent pairs.

    Explanation

    Multiplying the work of the nested passes gives quadratic growth.

  28. 28

    What is the best-case running time of bubble sort if it is modified to stop when a complete pass makes no swaps?

    Model answer

    It is Ω(n)\Omega(n)Ω(n) because even a sorted list requires one pass to check its n−1n-1n−1 adjacent pairs.

    Explanation

    With no swaps during that pass, the algorithm can stop early instead of making further passes.

  29. 29

    Why does the unoptimized bubble sort described in the content have a best-case running time of Ω(n2)\Omega(n^2)Ω(n2)?

    Model answer

    It performs its prescribed repeated passes even if the input is already sorted, so its work remains quadratic.

    Explanation

    Without an early-stop condition, sorted input does not reduce the number of passes.

  30. 30

    Describe the main steps of selection sort.

    Model answer

    Repeatedly find the smallest element in the unsorted portion and swap it into the next position in the sorted portion.

    Explanation

    Each iteration places one more smallest remaining element into its final position.

  31. 31

    Why can selection sort still take quadratic time when the input is already sorted?

    Model answer

    It must still scan the remaining elements to establish which one is smallest on each iteration.

    Explanation

    Seeing one small element does not prove it is the smallest until the rest of the unsorted portion has been checked.

  32. 32

    What are the big O and omega bounds for the selection sort described in the content?

    Model answer

    Both are quadratic: O(n2)O(n^2)O(n2) and Ω(n2)\Omega(n^2)Ω(n2).

    Explanation

    The repeated searches inspect successively smaller portions, totaling on the order of n2n^2n2 work even for favorable input.

  33. 33

    Why does finding the smallest element during selection sort require examining the whole unsorted portion?

    Model answer

    An element that appears smallest so far could be exceeded by a smaller unseen element, so the algorithm must check the rest of the portion.

    Explanation

    The algorithm cannot confirm the minimum until it has considered every remaining candidate.

  34. 34

    When selection sort moves the next smallest element into place, why might it swap with the element already there rather than shift every element over?

    Model answer

    Swapping avoids moving all the intervening elements, which would require extra work; the displaced element can be handled in a later iteration.

    Explanation

    The original list is unsorted, so moving the displaced element to another unsorted position is acceptable.

  35. 35

    How does bubble sort differ from selection sort in the way each builds a sorted list?

    Model answer

    Bubble sort repeatedly swaps out-of-order neighbors, while selection sort repeatedly finds the minimum remaining element and places it next in order.

    Explanation

    The algorithms use different strategies, although both have quadratic bounds in the versions described.

  36. 36

    How can sorting once and searching many times affect the choice between a slower sort and a faster search?

    Model answer

    The initial sorting cost may be worthwhile if repeated searches then benefit from a faster method such as binary search.

    Explanation

    Whether the trade-off pays off depends on how often the sorted data will be searched.

  37. 37

    What is recursion in programming?

    Model answer

    Recursion is a technique in which a function calls itself, typically on a smaller version of the original problem.

    Explanation

    A recursive function reduces a problem through successive calls and must include a stopping condition.

  38. 38

    What is a base case in a recursive function, and what purpose does it serve?

    Model answer

    A base case is a condition that stops further recursive calls and handles a simple instance directly.

    Explanation

    Without a base case, recursive calls could continue indefinitely.

  39. 39

    How can a pyramid of height hhh be defined recursively in terms of smaller pyramids?

    Model answer

    It can be defined as a pyramid of height h−1h-1h−1 followed by one additional row of hhh bricks.

    Explanation

    This definition reduces the task to drawing a smaller pyramid and then adding the current row.

  40. 40

    In a recursive pyramid-drawing function, what should happen when the requested height is 000?

    Model answer

    The function should return without drawing anything.

    Explanation

    A height of 000 is the base case that prevents the function from continuing to call itself.

  41. 41

    Why should a recursive call for drawing a pyramid use a smaller height than the original request?

    Model answer

    Reducing the height moves the function toward its base case, ensuring that the sequence of recursive calls eventually stops.

    Explanation

    For example, each call can reduce hhh to h−1h-1h−1 until it reaches 000.

  42. 42

    In the recursive pyramid example, why does the smallest row appear before the larger rows?

    Model answer

    The function makes recursive calls for smaller heights before printing the current row, so the calls reach the base case and then return outward, printing rows in increasing size.

    Explanation

    The rows are printed as the nested calls finish, not as they are first entered.

  43. 43

    What is the difference between iteration and recursion?

    Model answer

    Iteration repeats work using a loop, while recursion repeats work through a function calling itself.

    Explanation

    Both can express repeated processes, but they structure that repetition differently.

  44. 44

    What does it mean for an algorithm to use a divide-and-conquer approach?

    Model answer

    It breaks a problem into smaller parts, solves those parts, and may combine their results to solve the original problem.

    Explanation

    Binary search divides the search range; merge sort recursively sorts parts and then merges them.

  45. 45

    What are the three main steps of merge sort?

    Model answer

    Sort the left half, sort the right half, and merge the two sorted halves.

    Explanation

    The process is applied recursively until the sublists reach the base case.

  46. 46

    What is the base case for merge sort, and why is it valid?

    Model answer

    A list containing one item is returned as-is because a single item is already sorted.

    Explanation

    There is no pair of elements in a one-item list that could be out of order.

  47. 47

    How does merge sort combine two sorted lists into one sorted list?

    Model answer

    It repeatedly takes the smallest available front element from the two lists and appends it to the merged result.

    Explanation

    Because each input half is already sorted, comparing their next elements determines which belongs next.

  48. 48

    Why does merge sort require additional space during its merge step?

    Model answer

    It uses extra space to collect the elements from both sorted halves in their combined sorted order.

    Explanation

    The merged sequence is assembled separately before representing the combined sorted list.

  49. 49

    Why does dividing a list repeatedly in half lead to a logarithmic number of levels?

    Model answer

    Each division reduces the subproblem size by a factor of two, so the number of divisions needed to reach single-element lists grows logarithmically with the original size.

    Explanation

    For a list of size nnn, the number of halving levels is on the order of log⁡n\log nlogn.

  50. 50

    Why is merge sort’s running time O(nlog⁡n)O(n\log n)O(nlogn)?

    Model answer

    At each of about log⁡n\log nlogn levels, merging processes all nnn elements, giving total work proportional to nlog⁡nn\log nnlogn.

    Explanation

    The number of levels comes from repeated halving, and each level accounts for work across the list.

  51. 51

    What are the big O, omega, and theta bounds for the merge sort described in the content?

    Model answer

    They are O(nlog⁡n)O(n\log n)O(nlogn), Ω(nlog⁡n)\Omega(n\log n)Ω(nlogn), and therefore Θ(nlog⁡n)\Theta(n\log n)Θ(nlogn).

    Explanation

    The described algorithm performs the same recursive splitting and merging regardless of whether the input is already sorted.

  52. 52

    Why can merge sort be faster than bubble sort and selection sort for large lists, even though it does work at every level?

    Model answer

    Its nlog⁡nn\log nnlogn growth is asymptotically lower than the n2n^2n2 growth of bubble sort and selection sort.

    Explanation

    As input size increases, quadratic work grows more quickly than work proportional to nlog⁡nn\log nnlogn.

  53. 53

    What is a plurality election?

    Model answer

    It is an election in which the candidate with the most votes wins.

    Explanation

    A plurality method selects the candidate with the largest vote total.

  54. 54

    How does a runoff election differ from a simple plurality election as described in the content?

    Model answer

    A runoff can ask voters to rank candidates’ preferences, and the rankings are used to determine the winner rather than simply choosing the candidate with the most first-choice votes.

    Explanation

    The ranked preferences are adjudicated through an election algorithm or process.

  55. 55

    Why can the algorithm used to count or adjudicate votes affect an election’s outcome?

    Model answer

    Different vote-counting algorithms can interpret the same ballots differently and may therefore select different winners.

    Explanation

    The method for tallying votes and handling ranked preferences influences the result.

1 of 55
Question 1 of 55

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent