Searching and Sorting Algorithms
- 79Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is an algorithm, and what does sorting information mean?
79 questions
- 1
What is an algorithm, and what does sorting information mean?
Model answer
An algorithm is a step-by-step set of instructions for solving a problem. Sorting means arranging information according to an ordering rule, such as smallest to largest or alphabetical order.
Explanation
An algorithm describes a process for reaching a result, and sorting applies such a process to arrange data.
- 2
Why is counting people two at a time faster than counting them one at a time, yet still linear in the number of people?
Model answer
Counting two at a time reduces the number of steps by a constant factor, but the steps still increase proportionally with the number of people.
Explanation
A constant-factor speedup changes how steeply the time grows, not its linear growth pattern.
- 3
How does the pair-and-add attendance algorithm reduce the size of the problem at each round?
Model answer
Each person starts with a count of one; people pair up, add their counts, and one person in each pair sits down. This repeatedly combines counts while roughly halving the number of participants still standing.
Explanation
The remaining participants represent groups of increasing size, and the process continues until their counts can be combined into a total.
- 4
Why does the pair-and-add attendance algorithm take logarithmically many rounds?
Model answer
Each round roughly halves the number of participants still standing, so doubling the initial group requires only about one additional round.
Explanation
Repeated halving reaches one remaining group in a number of rounds proportional to log2N.
- 5
What is the divide-and-conquer principle illustrated by the attendance and phone-book examples?
Model answer
Divide and conquer repeatedly removes or solves a large portion of a problem, reducing it to smaller problems until the answer is reached.
Explanation
In the examples, halving the search space at each step leads to far fewer steps than examining every item individually.
- 6
What is the difference between an algorithm's correctness and its efficiency?
Model answer
Correctness concerns whether an algorithm produces the right result; efficiency concerns the resources it uses, such as time or memory.
Explanation
An algorithm can be correct but inefficient, so both properties matter when designing a solution.
- 7
Why do computer scientists compare how an algorithm's running time grows as the input grows?
Model answer
For small inputs, differences may be hard to notice, but for very large inputs, growth rates can make one algorithm much slower than another.
Explanation
The trend as input size increases is more informative than the time for just one small example.
- 8
Besides time, what other limited resources can be considered when evaluating an algorithm?
Model answer
Memory or storage space, money, and human effort can also be treated as costs.
Explanation
Algorithm design involves choosing how to use limited resources, not just minimizing running time.
- 9
Why can the pair-and-add attendance method be theoretically fast even if carrying it out in a large room is awkward?
Model answer
Its efficiency comes from reducing the number of participants through repeated pairing, not from how conveniently participants can communicate or perform the arithmetic.
Explanation
A real-world demonstration can have execution errors or practical delays without changing the algorithm's theoretical growth pattern.
- 10
When might it be preferable to use linear search rather than sort data and then use binary search?
Model answer
If the data needs to be searched only once and sorting it would take more time than searching directly, linear search may be preferable.
Explanation
The cost of sorting is worthwhile mainly when it can be offset by later searches or other benefits.
- 11
What does it mean to amortize the cost of sorting across many searches?
Model answer
It means that the initial sorting cost can be spread across many later searches, potentially making the overall approach worthwhile.
Explanation
Repeated use of sorted data, as in a frequently searched index, can justify paying the sorting cost once.
- 12
Why might a programmer knowingly choose a slower but simpler algorithm?
Model answer
A simpler algorithm may be adequate when the input is manageable or the result is not needed urgently, but its extra time should be an informed trade-off.
Explanation
Algorithm choices depend on the problem's resource constraints and the consequences of waiting or using more resources.
- 13
What is an array, and what is its defining memory-layout characteristic?
Model answer
An array is a data structure that stores values of the same type in a contiguous sequence of memory locations.
Explanation
The values are placed back-to-back in memory, which is the key characteristic described for arrays.
- 14
How does zero-based indexing affect the location of the last element in an array of N elements?
Model answer
The first element is at index 0, so the last element is at index N−1.
Explanation
Counting N elements starting at index 0 makes index N one past the end.
- 15
Why must a computer inspect array values one at a time in the simple model described?
Model answer
The computer must access each memory location to see its value; it cannot simply view the entire array at once.
Explanation
The locker analogy represents each value as hidden behind a separate door that must be opened to inspect it.
- 16
What are the input and desired output of the locker-search problem?
Model answer
The input is an array of lockers whose contents are initially unknown, and the desired output is a Boolean answer indicating whether the target value is present.
Explanation
The search should report either that the target was found or that it was not found.
- 17
Describe linear search and state whether it requires the data to be sorted.
Model answer
Linear search checks elements one at a time until it finds the target or reaches the end. It does not require sorted data.
Explanation
Because it makes no assumptions about order, it can examine an arbitrary array sequentially.
- 18
Why does searching from the opposite end not fundamentally improve linear search when the data is unordered?
Model answer
Without prior information about where the target is, either direction may require checking every element.
Explanation
Starting at the other end may be lucky for a particular arrangement, but it does not change the general strategy's growth.
- 19
Why can randomly opening lockers require extra memory or bookkeeping?
Model answer
The search may need to track which lockers have already been checked so it does not repeat work or miss lockers.
Explanation
A sequential search can progress in order without maintaining a separate record of visited locations.
- 20
What ordering condition makes binary search possible?
Model answer
The data must be sorted so that comparisons with a middle element identify which side can contain the target.
Explanation
Without an ordering, a less-than or greater-than comparison does not justify discarding either half.
- 21
Describe the main decision made at each step of binary search.
Model answer
Check the middle element; if it is not the target, compare the target with it and continue in the left or right half as appropriate.
Explanation
Each comparison eliminates the middle element and one entire half of the remaining search range.
- 22
Why should binary search exclude the middle element from the next search range after checking it?
Model answer
The middle element has already been checked, so searching it again would waste work.
Explanation
The remaining ranges should begin or end just beyond the tested middle location.
- 23
How can the index of the middle element in a range be found when integer indices are used?
Model answer
Take the midpoint of the range and round down to an integer index; for a range beginning at zero with seven elements, the middle index is 3.
Explanation
An array index must be an integer, and index 3 is the middle of indices 0 through 6.
- 24
What should a binary-search algorithm do when there are no elements left to search?
Model answer
It should return false, because the target cannot be found in an empty search range.
Explanation
This empty-range check also prevents the algorithm from continuing after its search space has been exhausted.
- 25
Why is it incorrect to return false immediately after the first unsuccessful comparison in linear search?
Model answer
The target may be in a later element, so the search must continue through the array before concluding it is absent.
Explanation
Returning from a function ends its execution; an early false result would skip all remaining elements.
- 26
Why can a final return false correctly follow the loop in linear-search pseudocode?
Model answer
If execution reaches that statement, the loop has checked every element without finding the target.
Explanation
The final false result is therefore justified only after the complete search fails.
- 27
Why does binary search fail on an unsorted array?
Model answer
Its decision to discard one half depends on the data being ordered; in an unsorted array, the target may be in the half it discards.
Explanation
The comparisons no longer provide valid information about where smaller or larger values are located.
- 28
What do big O, big Omega, and big Theta describe?
Model answer
Big O describes an upper bound on growth, Omega describes a lower bound, and Theta describes a tight bound when the upper and lower bounds match.
Explanation
These forms of asymptotic notation summarize how an algorithm's cost grows as input size becomes large.
- 29
Why is big O commonly discussed in terms of a worst-case input?
Model answer
The upper bound indicates how costly the algorithm can become, and the worst case shows how many steps may be needed when the input is unfavorable.
Explanation
A worst-case analysis provides a useful guarantee about the algorithm's potential cost.
- 30
What does it mean to ignore lower-order terms when using big O notation?
Model answer
It means focusing on the term that dominates growth for large inputs and omitting terms that become relatively less important.
Explanation
As input size increases, the dominant term has the greatest influence on the total cost.
- 31
Why are O(N) and O(N/2) treated as the same growth class?
Model answer
Dividing by a fixed constant changes the number of steps by a constant factor, but both costs grow linearly with N.
Explanation
Big O focuses on growth as the input becomes large, rather than constant-factor differences.
- 32
Why is the base of the logarithm usually omitted in big O descriptions?
Model answer
Logarithms with different constant bases differ only by a constant factor, which big O ignores.
Explanation
Thus logarithmic growth can be written as O(logN) without specifying the base.
- 33
What are the best-case and worst-case running times of linear search?
Model answer
Its best case is �Ω(1) and its worst-case upper bound is O(N).
Explanation
The target may be the first item, but it may also be the last or absent, requiring a scan of the array.
- 34
What are the best-case and worst-case running times of binary search on sorted data?
Model answer
Its best case is Ω(1) and its worst-case upper bound is O(logN).
Explanation
The target might be at the first middle position checked, while repeated halving takes logarithmically many checks in the worst case.
- 35
Why does binary search become much faster than linear search for large sorted inputs?
Model answer
Linear search may inspect a number of elements proportional to N, while binary search repeatedly halves the search range and takes on the order of logN steps.
Explanation
The gap between linear and logarithmic growth becomes more significant as the input gets larger.
- 36
When can an algorithm be described by Theta notation?
Model answer
It can be described by Theta notation when its upper and lower asymptotic bounds are the same growth class.
Explanation
Theta communicates both bounds together as a tight description of growth.
- 37
Why are phone numbers often stored as strings rather than integers?
Model answer
Phone numbers may contain punctuation or leading zeros, which strings preserve but integer representations do not handle as meaningful formatting.
Explanation
A phone number is an identifier, not necessarily a quantity used in arithmetic.
- 38
Why does comparing two strings in C require a different approach from comparing two integers?
Model answer
A string consists of multiple characters, so equality requires comparing their character contents rather than treating each string like a single integer value.
Explanation
A string comparison function can inspect the characters to determine whether the strings match.
- 39
What does the C function
strcmpreport when two strings are equal, and what can its other results indicate?Model answer
It returns 0 when the strings are equal; a negative or positive result indicates an ordering difference between them.
Explanation
The ordering result can be used to determine which string comes first according to character values.
- 40
What header is needed to use
strcmpin the example, and what happens if it is omitted?Model answer
Include
string.h; without it, the compiler may report that the function is undeclared.Explanation
The header provides the function declaration that tells the compiler about
strcmp. - 41
Why can two parallel arrays for names and phone numbers be a fragile design?
Model answer
Their relationship depends on matching indices and maintaining the same length and order, so a mismatch can associate a person with the wrong number.
Explanation
Keeping related data in separate arrays relies on programmers consistently maintaining an external correspondence.
- 42
What problem does a structure solve when representing a person in a phone book?
Model answer
A structure groups related fields, such as a person's name and phone number, into one value.
Explanation
Grouping the fields helps keep each person's information together instead of relying on separate parallel arrays.
- 43
What is the purpose of
typedef structin the person example?Model answer
It defines a new named type,
person, containing fields for a name and a number.Explanation
Once defined, the custom type can be used to declare individual people or arrays of people.
- 44
How does dot notation access a field in a structure?
Model answer
Use the structure value followed by a dot and the field name, such as
people[i].name.Explanation
The dot selects a particular member of the structure at the specified array index.
- 45
How does an array of structures improve the organization of a phone book?
Model answer
Each array element represents one person and contains that person's related fields together.
Explanation
The design makes the connection between a person's name and number part of the same structured record.
- 46
Why can an array's size be inferred when it is initialized with values in braces?
Model answer
The compiler can count the initial values and use that count as the array length.
Explanation
Inferring the size avoids manually specifying a length that could disagree with the number of supplied values.
- 47
What is selection sort's basic strategy?
Model answer
For each position, find the smallest element in the unsorted portion and swap it into that position.
Explanation
Repeatedly selecting the next smallest remaining element builds a sorted section from left to right.
- 48
Why does selection sort swap the smallest element with the current position instead of simply inserting it there?
Model answer
An array has fixed allocated positions, so the algorithm swaps the selected element with the value already occupying the target position.
Explanation
The swap places the selected value without requiring unallocated space to open up within the array.
- 49
What does the index range from i through N−1 represent in selection sort?
Model answer
It represents the unsorted portion in which selection sort searches for the smallest element for position i.
Explanation
Earlier positions have already been filled with the smallest values found so far.
- 50
Why does selection sort repeat its search even when the input is already sorted?
Model answer
Its basic procedure does not check whether the array is already sorted; it continues finding the minimum in each remaining portion.
Explanation
The algorithm follows its prescribed passes regardless of the initial order.
- 51
How many comparisons does selection sort make across its passes, and what is its asymptotic running time?
Model answer
Its comparisons sum to (N−1)+(N−2)+⋯+1, which grows as O(N2).
Explanation
The total is proportional to N(N−1)/2, whose dominant term is quadratic.
- 52
What are the upper, lower, and tight asymptotic bounds for the selection sort described?
Model answer
Its bounds are O(N2) and Ω(N2), so its tight bound is Θ(N2).
Explanation
The same repeated search work is required even in the best case when the data starts sorted.
- 53
What is bubble sort's basic strategy?
Model answer
It repeatedly compares adjacent elements and swaps any pair that is out of order, causing large elements to move toward the end.
Explanation
Repeated passes move elements through neighboring positions until the list is sorted.
- 54
Why does a bubble-sort loop comparing indices i and i+1 stop before N−1?
Model answer
If i were N−1, then i+1 would be N, an index outside an array whose last valid index is N−1.
Explanation
The loop must stop early enough that both elements in each adjacent pair are valid array locations.
- 55
Why does the basic bubble-sort algorithm need repeated passes?
Model answer
A single pass can move the largest remaining element to the end, but other elements may still be out of order.
Explanation
Further passes move additional elements into their correct positions.
- 56
What is the worst-case running time of bubble sort as described?
Model answer
Its worst-case running time is O(N2).
Explanation
It makes a number of passes proportional to N, with each pass doing a number of comparisons proportional to N.
- 57
How can bubble sort be modified to stop early when the list is already sorted?
Model answer
Track whether a pass makes any swaps and stop if a complete pass makes none.
Explanation
If no adjacent pair needed swapping, the list is already in order.
- 58
What are the best-case and worst-case bounds for bubble sort with the no-swap optimization?
Model answer
Its best-case lower bound is Ω(N), while its worst-case upper bound remains O(N2).
Explanation
Even when the list is sorted, one pass must check its elements; unfavorable inputs can still require many passes.
- 59
Why does the optimized bubble sort not have a tight bound of Θ(N)?
Model answer
Its best-case growth is linear, but its worst-case growth is quadratic, so the upper and lower bounds do not match.
Explanation
Theta notation requires the same asymptotic growth for both bounds.
- 60
What is recursion in programming?
Model answer
Recursion is a technique in which a function calls itself.
Explanation
A recursive function solves a problem by invoking another instance of itself, often with a smaller input.
- 61
What is the difference between a recursive case and a base case?
Model answer
A recursive case calls the function again on a smaller problem; a base case gives an immediate result and stops further recursion.
Explanation
The base case prevents recursive calls from continuing indefinitely.
- 62
Why must recursive calls make progress toward a base case?
Model answer
If each call receives the same-sized problem, it may never terminate; smaller problems can eventually reach the stopping condition.
Explanation
Progress in problem size is what allows the recursion to bottom out.
- 63
How can a pyramid be defined recursively?
Model answer
A pyramid of height N can be defined as a pyramid of height N−1 plus one additional row, with a single brick serving as a base case.
Explanation
Each larger pyramid is described in terms of a smaller one until the simplest structure is reached.
- 64
How does iteration differ from recursion as a problem-solving technique?
Model answer
Iteration uses loops to repeat steps, whereas recursion repeats work through function calls that invoke the same function.
Explanation
Both can solve repeated or progressively smaller tasks, but they express the process differently.
- 65
What base case can stop a recursive pyramid-drawing function from drawing below height zero?
Model answer
Return immediately when the height is less than or equal to zero.
Explanation
This condition handles the zero-height stopping point and prevents drawing for negative heights.
- 66
Why can a recursive solution use more memory than an iterative solution?
Model answer
Each active recursive call uses memory to keep track of its function state, so many nested calls can consume substantial memory.
Explanation
An iterative loop can perform repeated work without accumulating the same chain of active function calls.
- 67
How can an unbounded chain of recursive calls affect a program?
Model answer
It can exhaust available memory and cause the program to fail.
Explanation
Each call consumes additional memory, so recursion must terminate and its depth must remain manageable.
- 68
In recursive binary search, why do calls to search the left or right half not create an infinite loop?
Model answer
Each recursive call searches a smaller range, and an empty range provides a base case that returns false.
Explanation
The search range keeps shrinking until the target is found or no elements remain.
- 69
How does a recursive formulation of phone-book search differ from a loop-based formulation?
Model answer
The loop-based version directs execution back to earlier steps, while the recursive version calls the same search procedure on a smaller half of the book.
Explanation
Both express repeated search, but recursion describes the repetition by reapplying the algorithm to a smaller problem.
- 70
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 first two steps recursively sort smaller parts, and the final step combines them in order.
- 71
What is the base case for merge sort, and why does it work?
Model answer
A list containing one element is the base case because it is already sorted.
Explanation
No rearrangement is needed for a single-element list, so recursion can stop there.
- 72
How are two sorted lists merged?
Model answer
Compare the first unprocessed element of each list, move the smaller one to the output, and advance in the list it came from.
Explanation
Because each input list is already sorted, its first remaining element is the smallest remaining candidate in that list.
- 73
Why does merging two sorted lists of total size N take O(N) time?
Model answer
Each element is selected and moved to the merged result once, so the work is proportional to the total number of elements.
Explanation
The merge advances through the lists rather than repeatedly rescanning their elements.
- 74
Why is merge sort considered a divide-and-conquer algorithm?
Model answer
It divides the input into smaller halves, solves those smaller sorting problems recursively, and combines their results.
Explanation
The algorithm applies the same strategy at successively smaller problem sizes.
- 75
Why does merge sort make fewer repeated comparisons than selection sort or bubble sort?
Model answer
It sorts smaller lists separately and then merges them, processing elements in an organized pass rather than repeatedly comparing many of the same elements.
Explanation
At each merge level, elements are combined in order with a linear scan.
- 76
Why does merge sort require additional space?
Model answer
It needs extra storage to hold the elements while merging the sorted halves.
Explanation
The merging process places the selected elements into a separate output area before producing the combined list.
- 77
How many merge levels are needed when merge sort repeatedly halves a list of N elements?
Model answer
The number of levels is proportional to log2N.
Explanation
Each level halves the problem size until the sublists contain one element each.
- 78
What is merge sort's running time, and how does that compare with quadratic sorting algorithms?
Model answer
Merge sort takes Θ(NlogN) time, which grows more slowly than the Θ(N2) time of selection sort and the worst case of bubble sort.
Explanation
Merge sort performs linear merging work across logarithmically many levels.
- 79
Why can merge sort be described using Theta notation?
Model answer
Its upper and lower bounds are both NlogN, so its tight bound is Θ(NlogN).
Explanation
The described merge sort does not include a shortcut that changes its growth for already sorted input.

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