Searching and Sorting Algorithms
- 83Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
- spaceFlip card
- KI knew it
- DI didn't know it
- ←Previous card
- →Next card
What is an algorithm?
A step-by-step set of instructions for solving a problem.
Or swipe the card
83 cards
What is an algorithm?
A step-by-step set of instructions for solving a problem.
What does sorting information mean?
Ordering it according to a chosen rule, such as smallest to largest or alphabetically.
How does the pair-and-add attendance algorithm work?
Everyone starts with 1; standing participants pair up, add their values, and one sits down. Repeat with the remaining standing participants until the values have been aggregated.
Why does pair-and-add attendance counting take about log2N rounds?
Each round roughly halves the number of standing participants, so doubling the group requires only about one additional round.
What does the attendance-counting example illustrate about algorithm design?
A carefully designed algorithm can scale much better than counting each item individually, even when both methods solve the same problem.
What does algorithmic cost mean?
The resources an algorithm uses, such as time, money, or storage space.
Why do computer scientists analyze how an algorithm's running time grows?
Differences may be negligible for small inputs but become important as input size grows substantially.
What is the relationship between the size of an array and its zero-based indices?
An array with N elements has indices from 0 through N−1; index N would be one past its end.
Why can an algorithm that is correct but slow sometimes be a reasonable choice?
If a result is needed only once, the cost of preparing data for a faster search may outweigh the benefit.
When can sorting data before repeated searches be worthwhile?
When the data will be searched many times, the sorting cost can be amortized across those searches.
What does it mean to make an informed algorithm trade-off?
Choose among costs such as time, memory, and preparation deliberately, based on the problem and how often the result is needed.
Why might a bug in a slow-running program be especially costly?
The program may run for a long time before revealing the bug, wasting the time spent waiting for its result.
What is an array?
A data structure that stores values of the same type in consecutive locations in memory.
How does a computer access values in the basic array model?
It accesses one value at a time by going to its location and reading it; it does not simply see every value at once.
What is zero indexing?
Numbering array locations starting at 0 rather than 1.
How many locations are implied by the array index 6?
At least 7 locations, because indexing starts at 0.
What output did the locker-search problem ask for?
A Boolean result indicating whether the target value was present: true if found and false otherwise.
How does linear search work?
Check values one by one, moving consistently from one end of the data to the other, until the target is found or no values remain.
Why is searching from right to left not fundamentally different from searching from left to right?
Without prior information about the data, either direction may find the target sooner by chance, but both may need to check every item.
Why can randomly checking lockers require extra bookkeeping?
You may need to remember which lockers have already been checked so you do not repeat work or overlook one.
What prerequisite allows binary search to discard half the search space?
The data must be sorted, so comparisons with the middle value indicate which half could contain the target.
What does binary search do after checking the middle value?
If the target is smaller, search the left half; if larger, search the right half; if equal, return that it was found.
Why does binary search exclude the middle element from the next search range?
The middle element has already been checked, so searching it again would waste work.
How can an algorithm compute the middle index of an integer-indexed range?
Divide the relevant index calculation by 2 and round down; for example, the middle index of 7 positions starting at 0 is 3.
What should binary search do if there are no elements left to search?
Return false, because the target cannot be found in an empty search range.
Why is binary search on an unsorted array incorrect?
The comparison with the middle value gives no reliable reason to choose the left or right half, so the target could be discarded mistakenly.
Why can a C array be initialized without specifying its size in square brackets?
When values are supplied in the initializer braces, the compiler can count them and infer the array size.
How can a C program perform linear search over an array?
Use a loop to visit each index and compare the value there with the target; report success if a match is found and failure after the loop otherwise.
Why should a linear-search failure result come after the loop rather than immediately after the first mismatch?
A mismatch at one position does not rule out a match later in the array. Returning failure immediately would stop the search too soon.
What does returning a value from a C function do?
It ends that function's execution and passes the return value to its caller.
What do return values of 0 and nonzero values conventionally indicate when returned from C's
main?0 conventionally indicates success; a nonzero value indicates an error or unsuccessful outcome.
Why does
==not correctly compare C strings?A string contains multiple characters;
==does not compare the character contents as a string comparison requires.What does C's
strcmpfunction do?It compares two strings and returns 0 when they are equal, a negative value when the first precedes the second, and a positive value when it follows the second.
Which header is needed to use
strcmpin C?Include
string.h.Why can
strcmpbe useful for more than checking whether strings match?Its negative or positive result indicates the relative ordering of the strings, which can help compare them for sorting.
Why are phone numbers often stored as strings rather than integers?
They can contain punctuation and leading zeros, which integers cannot preserve as part of the value.
What problem can arise from storing names and phone numbers in separate arrays?
The arrays must remain the same length and in matching order; if they become misaligned, a name may be paired with the wrong number.
What is a C
structused for?It defines a custom data type that groups related fields, such as a person's name and phone number.
How do you access a field of a C structure variable?
Use the dot operator, as in
person.name.How can a structure improve a phone-book representation?
Each array element can hold one person's related information together, reducing reliance on separate arrays staying aligned.
What does Big O notation describe?
An asymptotic upper bound on how an algorithm's resource use grows with input size.
What does Big Omega notation describe?
An asymptotic lower bound on how an algorithm's resource use grows with input size.
When can an algorithm's running time be described using Theta notation?
When its Big O upper bound and Big Omega lower bound have the same asymptotic growth rate.
What is asymptotic notation concerned with?
How an algorithm's resource use behaves as the input size becomes very large.
When simplifying a running-time expression for Big O, which terms matter most?
The dominant term; constant factors and lower-order terms are ignored.
Why are O(N) and O(N/2) treated as the same growth class?
Both grow linearly with N; Big O ignores constant factors.
Why is the base of a logarithm typically omitted in Big O notation?
Changing the logarithm's base changes its value only by a constant factor, which Big O ignores.
What is the worst-case running time of linear search?
O(N), because the target may be at the last position or absent, requiring a scan of all N values.
What is the best-case running time of linear search?
Ω(1), because the target may be the first value checked.
What is the worst-case running time of binary search on sorted data?
O(logN), because each comparison can reduce the remaining search range by about half.
What is the best-case running time of binary search?
Ω(1), when the first middle value checked is the target.
Why is Big O often discussed in relation to worst-case performance?
The upper bound shows how much work an algorithm might require when the data or target gives it an unfavorable case.
How does selection sort choose the next element to place?
On each pass, it finds the smallest value in the unsorted portion and swaps it into the next position.
After selection sort places the smallest value at index 0, what range does it search next?
It searches the remaining unsorted range, starting at index 1, for the next-smallest value.
Why does selection sort swap values rather than make room by shifting the whole array?
An array has a fixed allocated range; the algorithm cannot assume it can use memory beyond that range.
How many comparisons does selection sort perform in total?
It performs (N−1)+(N−2)+⋯+1=2N(N−1) comparisons.
What are the Big O, Big Omega, and Theta running times of selection sort?
All are Θ(N2): its comparison work remains quadratic even when the input is already sorted.
How does bubble sort make progress toward sorting a list?
It compares neighboring values and swaps each pair that is out of order; repeated passes move large values toward the end.
Why does bubble sort's inner loop stop before index N−1?
It compares index i with i+1; if i=N−1, then i+1=N would be outside the array.
Why does bubble sort make repeated passes?
A pass moves a largest remaining value to the end, but the other values may still be out of order.
What is the worst-case running time of bubble sort?
O(N2), because it can perform a linear number of comparisons on each of a linear number of passes.
How can bubble sort stop early when the list is already sorted?
Track whether a pass made any swaps; if it made none, stop because the list is already in order.
What is the best-case running time of bubble sort with the no-swap early-stop improvement?
Ω(N), because it must make a pass through the list to establish that no swaps are needed.
What is the Theta running time of selection sort, and why can it be stated with Theta?
Θ(N2), because both its upper and lower bounds are quadratic.
What trade-off can arise between an algorithm's running time and memory use?
Using extra memory can sometimes reduce work or running time; saving memory can require doing more work.
What is recursion in programming?
A technique in which a function calls itself.
What is a recursive case?
A part of a recursive solution that calls the same function on a smaller version of the problem.
What is a base case in recursion?
A condition that gives an immediate answer and stops further recursive calls.
Why must recursive calls make progress toward a base case?
If each call receives the same-size problem, the function may call itself indefinitely; reducing the problem allows it eventually to stop.
How can binary search be expressed recursively?
Check the middle value; if the target is not there, call the search again on the appropriate, smaller half.
How does the recursive view of phone-book search differ from an iterative view?
The recursive view says to search the appropriate half again; the iterative view directs execution back to earlier steps using a loop.
How can a pyramid of height N be defined recursively?
As a pyramid of height N−1 followed by one additional row, with a single brick serving as a possible base case.
What is iteration in programming?
Solving a problem by repeating instructions using loops.
How can an iterative program print a pyramid whose row widths increase from 1 to N?
Use an outer loop for rows and an inner loop to print the row's bricks, then print a newline after each row.
What base case can prevent a recursive pyramid-drawing function from calling itself forever?
If the requested height is less than or equal to 0, return without drawing anything.
Why can a recursive program use more memory than an iterative version?
Each active function call uses memory; sufficiently many nested calls can exhaust available memory.
What is the base case for merge sort?
A list with one element is already sorted, so no further work is needed.
What are the main steps of merge sort?
Sort the left half, sort the right half, and merge the two sorted halves.
How do you merge two already-sorted lists?
Compare the first unmerged value in each list, move the smaller one to the result, and repeat; when one list is exhausted, append the remainder of the other.
Why can two sorted lists be merged in O(N) time?
Each value can be examined and moved once, so the work is proportional to the total number of values.
What is the running time of merge sort?
Θ(NlogN): each level of splitting and merging processes N values, and there are about log2N levels.
Why does merge sort require extra memory?
Merging uses additional space to hold and combine the sorted halves.
Why does merge sort generally perform fewer repeated comparisons than selection sort or bubble sort?
It recursively sorts smaller portions and merges them, rather than repeatedly scanning the same values to fix one position or neighboring pair at a time.

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