Week 3: Algorithms
- 46Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
- spaceFlip card
- KI knew it
- DI didn't know it
- ←Previous card
- →Next card
What is the key property of an array in memory?
An array is a contiguous sequence of values stored back-to-back in memory.
Or swipe the card
46 cards
What is the key property of an array in memory?
An array is a contiguous sequence of values stored back-to-back in memory.
How is memory typically addressed in a computer?
Memory is addressed sequentially from byte 0 to byte n-1, where n is the total number of bytes.
What simplification does CS50 make about a computer's ability to access memory?
The computer can only look at one memory location at a time.
What is linear search?
Linear search is an algorithm that checks each element of an array one by one from left to right until the target is found or the end is reached.
What is the pseudocode for linear search?
For each door from left to right: if 50 is behind door: return true return false
(The return false must be after the loop, not inside it.)
What is binary search and what requirement does it have?
Binary search repeatedly divides the search interval in half. It requires the data to be sorted.
Give the pseudocode for binary search on an array 'doors'.
If no doors left: return false If 50 is behind doors[middle]: return true Else if 50 < doors[middle]: search doors[0] through doors[middle-1] Else if 50 > doors[middle]: search doors[middle+1] through doors[n-1]
Compare the worst-case number of steps for linear search and binary search with n elements.
Linear search: O(n) steps. Binary search: O(log n) steps.
What is binary search's requirement regarding data order?
Binary search requires the data to be sorted (e.g., smallest to largest). It does not work on unsorted/random data.
What does big O notation represent?
Big O notation represents the upper bound (worst-case) on the running time of an algorithm, describing its growth rate as input size n increases.
What does big Omega notation represent?
Big Omega notation represents the lower bound (best-case) on the running time of an algorithm.
What does big Theta notation represent?
Big Theta notation is used when the upper bound (big O) and lower bound (big Omega) are the same, meaning the algorithm's running time is asymptotically tight.
What is the worst-case (big O) running time of linear search?
O(n), where n is the number of elements.
What is the best-case (big Omega) running time of linear search?
Omega(1).
What is the worst-case (big O) running time of binary search?
O(log n).
What is the best-case (big Omega) running time of binary search?
Omega(1).
What are the worst-case and best-case running times of selection sort (as commonly implemented without early termination)?
Both worst-case and best-case are Theta(n^2).
What is the worst-case running time of bubble sort?
O(n^2).
What is the best-case running time of bubble sort with an optimization that checks if any swaps were made?
Omega(n).
What is the worst-case and best-case running time of merge sort (without early termination)?
Both worst-case and best-case are Theta(n log n).
Describe the selection sort algorithm.
- For i from 0 to n-1: a. Find the smallest element between positions i and n-1. b. Swap that smallest element with the element at position i.
- After each pass, the first i+1 elements are sorted.
Describe the bubble sort algorithm.
- Repeat n-1 times: a. For i from 0 to n-2: i. If numbers[i] > numbers[i+1], swap them.
- After each pass, the largest element among the unsorted portion 'bubbles' to the end.
What is the optimization for bubble sort?
After each pass, check if any swaps were made. If no swaps were made, the array is sorted and the algorithm can terminate early.
Describe the merge sort algorithm.
- If the array has 1 or 0 elements, it is already sorted (base case).
- Otherwise: a. Sort the left half. b. Sort the right half. c. Merge the two sorted halves into one sorted array.
How does the merge step in merge sort work?
Compare the first elements of the two sorted halves. Take the smaller element and place it in the result. Repeat until both halves are exhausted.
What is the running time of the merge step in merge sort?
O(n) where n is the total number of elements in the two halves combined.
Why is merge sort O(n log n)?
The array is divided in half log n times, and at each level of division, merging all pairs takes O(n) total, so total time is O(n log n).
What is a trade-off of merge sort compared to selection or bubble sort?
Merge sort uses extra memory (O(n) additional space) for merging, whereas selection and bubble sort sort in place.
What is a recursive algorithm?
A recursive algorithm is one that calls itself on a smaller version of the problem until reaching a base case.
What are base case and recursive case in recursion?
A base case is the simplest instance of the problem that can be solved directly without further recursion. A recursive case reduces the problem size and calls the function again.
Give an example of a recursive algorithm from the lecture.
Binary search can be implemented recursively: search(left half) or search(right half) after comparing the middle element.
How can a pyramid of height n be defined recursively?
A pyramid of height n is a pyramid of height n-1 plus one additional row of n bricks at the bottom.
What is the base case for the recursive pyramid drawing algorithm?
If n == 0, do nothing (return).
What is a potential problem with the Google recursion Easter egg?
It creates an infinite loop because it suggests searching for 'recursion' again, with no base case.
What is a struct in C?
A struct is a user-defined data type that groups together multiple variables (fields) of possibly different types under one name.
How do you access a field of a struct variable?
Using the dot operator: variable.fieldname. For example, people[0].name.
What is the strcmp function and how is it used to compare strings?
strcmp(s1, s2) compares two strings. It returns 0 if they are equal, a negative number if s1 comes before s2 (alphabetically/ASCII-betically), and a positive number if s1 comes after s2.
Why should phone numbers be stored as strings rather than integers?
Phone numbers may contain hyphens, parentheses, or plus signs, and it does not make sense to perform arithmetic on them. Hence they are better stored as strings.
What are parallel arrays and what is a disadvantage?
Parallel arrays are multiple arrays of the same length where corresponding indices hold related data (e.g., one array for names and one for numbers). The disadvantage is that maintaining alignment is error-prone.
Write C code to implement linear search for an integer in an array.
int numbers[] = {20, 500, 10, 5, 100, 1, 50}; int n = get_int("Number: "); for (int i = 0; i < 7; i++) { if (numbers[i] == n) { printf("Found\n"); return 0; } } printf("Not found\n"); return 1;
Write C code to implement linear search for a string in an array of strings using strcmp.
string strings[] = {"battleship", "boot", "cannon", "iron", "thimble", "top hat"}; string s = get_string("String: "); for (int i = 0; i < 6; i++) { if (strcmp(strings[i], s) == 0) { printf("Found\n"); return 0; } } printf("Not found\n"); return 1;
(Note: Must #include <string.h>)
Write C code to implement a phonebook using two parallel arrays (names and numbers) and linear search.
string names[] = {"Yuliia", "David", "John Harvard"}; string numbers[] = {"+1-617-495-1000", "+1-617-495-1000", "+1-949-468-2750"}; string name = get_string("Name: "); for (int i = 0; i < 3; i++) { if (strcmp(names[i], name) == 0) { printf("Found %s\n", numbers[i]); return 0; } } printf("Not found\n"); return 1;
Write C code to implement a phonebook using an array of structs (person) with name and number fields.
#include <cs50.h> #include <stdio.h> #include <string.h>
typedef struct { string name; string number; } person;
int main(void) { person people[3]; people[0].name = "David"; people[0].number = "+1-617-495-1000"; people[1].name = "John Harvard"; people[1].number = "+1-949-468-2750"; people[2].name = "Yuliia"; people[2].number = "+1-617-495-1000";
string name = get_string("Name: "); for (int i = 0; i < 3; i++) { if (strcmp(people[i].name, name) == 0) { printf("Found %s\n", people[i].number); return 0; } } printf("Not found\n"); return 1;}
What is the trade-off between developer time and algorithm efficiency?
Sometimes it is faster to write a simpler, less efficient algorithm (e.g., bubble sort) and let it run, rather than spending more time to implement a more efficient algorithm (e.g., merge sort).
When is it worth sorting data before searching?
If you need to search the data many times, it is worth sorting once (e.g., O(n log n) with merge sort) to enable fast binary search (O(log n)) per query, rather than using linear search (O(n)) each time.
What is the space-time trade-off in merge sort?
Merge sort has O(n log n) time but requires O(n) extra space for merging, whereas selection and bubble sort use O(1) extra space but have O(n^2) time.

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