1. Home
  2. Explore
  3. Computer Science
  4. Data Structures and Algorithms

Study methods

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

Data Structures and Algorithms

Speaker 1Speaker 2

Data Structures and Algorithms

13:55
0:00-13:55
  1. Anna

    Let's begin with a basic idea: an algorithm is a set of step-by-step instructions for solving a problem. We have already seen algorithms for searching a phone book, but there is another question that matters just as much: how is the data arranged in memory?

  2. Michael

    Right. In the physical phone book, names and numbers are printed on pages. In a computer, everything is ultimately represented by zeros and ones stored in memory. The way those bits and bytes are laid out can have a major effect on an algorithm's performance, even when the algorithm is logically correct.

  3. Anna

    To make that concrete, imagine seven doors, each hiding an integer, and suppose we are searching for 50. If the numbers behind the doors are in random order, we have no useful clue about where 50 might be. We may have to open nearly every door, so in the worst case the search takes about n steps for n doors.

  4. Michael

    And guessing a door is not a reliable algorithm. You could happen to choose 50 immediately, but with seven randomly placed numbers, that is only a one-in-seven chance. An algorithm needs reproducible performance, not a lucky outcome that cannot be counted on.

  5. Anna

    The phone book gives us an advantage because the phone company has done work in advance: names are sorted alphabetically. With sorted data, we can use binary search. We check the middle, determine whether the target is smaller or larger, discard half the possibilities, and repeat.

  6. Michael

    For the sorted seven doors, checking the middle might reveal 16. Since 50 is larger, we ignore everything to the left. The middle of the remaining three might be 42, and because 50 is larger again, only the final door remains. That finds 50 in three checks instead of as many as six.

  7. Anna

    As the number of doors grows, that difference becomes much more important. Linear search may require n steps, while binary search repeatedly halves the problem and takes logarithmic time, often written log base 2 of n. But binary search depends on two conditions: the data must be sorted, and the elements must be arranged back-to-back so their positions can be accessed efficiently.

  8. Michael

    That back-to-back arrangement is called an array. An array is a contiguous block of memory in which values are stored next to one another. Because every element occupies a predictable amount of space, a computer can use arithmetic to calculate where an element is located.

  9. Anna

    Computers also normally count positions from zero. With seven elements, the indexes are 0 through 6. To find the middle, the computer can calculate 7 divided by 2, round down to 3, and access index 3. If three elements remain, 3 divided by 2 rounds down to 1, so the computer accesses the middle of that smaller section.

  10. Michael

    This is where random access comes in. In RAM, the computer can jump to a particular byte or address in constant time, meaning the access takes a fixed amount of time independent of how large the overall data set is. The word 'random' in RAM refers to this ability to access any address directly, not to the data being randomly ordered.

  11. Anna

    Bytes are groups of bits, commonly eight bits per byte, and memory addresses let the computer identify those bytes. If array elements are contiguous and equal in size, simple addition, division, and rounding allow the computer to calculate the address of an element. If the values were scattered unpredictably, the same calculation would not tell the computer where to jump.

  12. Michael

    The phone book is a physical example with some of the same useful properties: its pages are arranged back-to-back and its names are sorted. That supports the three familiar search strategies. Checking one page at a time is linear, checking in larger but logically limited steps can be described differently, and dividing the remaining problem in half gives logarithmic binary search.

  13. Anna

    Computer scientists use formal notation to describe these running times. Big O expresses an upper bound, or how much time an algorithm may require in the relevant worst-case sense. Linear search is O of n, because in the worst case the target is at the end or is not present.

  14. Michael

    Omega expresses a lower bound, often discussed through the best case. Linear search has an omega of 1 because the target might be the very first element. Theta is used when the upper and lower bounds coincide, so an algorithm can be characterized tightly by the same formula from both directions.

  15. Anna

    Now, sorting is the work that makes binary search possible, and sorting also has its own costs. Imagine eight numbered cups shuffled into a random order. One approach is to compare neighboring cups and swap them whenever they are out of order.

  16. Michael

    That is bubble sort. You repeatedly scan from left to right, comparing adjacent elements. Each swap fixes a local mistake, and after enough passes, larger values appear to bubble toward one end while smaller values move toward the other. You can stop once a complete pass makes no swaps.

  17. Anna

    Its pseudocode is: repeat until there are no swaps; for i from 0 to n minus 2, if the i-th and i-plus-one elements are out of order, swap them. We stop at n minus 2 because each comparison also looks at the next position, i plus 1, and the final valid index is n minus 1.

  18. Michael

    The other cup-based method is selection sort. Instead of repeatedly fixing adjacent pairs, selection sort scans the unsorted portion to find the smallest remaining value. It places that value at the next position, then repeats on the remaining elements.

  19. Anna

    Selection sort can be described as: for i from 0 to n minus 1, find the smallest element from index i through index n minus 1, then swap it with the element at index i. Each pass reduces the unsorted portion by one element.

  20. Michael

    Both methods take quadratic time, or O of n squared, in the general analysis being presented. Bubble sort may compare roughly n minus 1 adjacent pairs on each of roughly n passes. Selection sort performs about n minus 1 comparisons, then n minus 2, then n minus 3, and so on.

  21. Anna

    That selection-sort sum is n times n minus 1, divided by 2, which is n squared over 2 minus n over 2. As n becomes very large, the n squared term dominates the linear term, so we describe the algorithm as being on the order of n squared and write O of n squared.

  22. Michael

    The square matters. For one million elements, that comparison count is 499,999,500,000, which is close in scale to half a trillion. So even though the exact count is not simply n squared, the quadratic growth gives us a useful picture of why these methods become slow.

  23. Anna

    Could we sort faster by dividing the data into smaller pieces, just as binary search divides a search problem? Yes, but sorting cannot simply discard half the data, because every element still has to be placed. One faster approach is merge sort.

  24. Michael

    Merge sort divides the list into halves, then divides those halves again and again until it reaches individual elements. A single element is already sorted. It then merges the small sorted pieces into larger sorted pieces, continuing until the entire list has been reassembled.

  25. Anna

    Merge sort is faster than bubble sort and selection sort in the comparison presented: its running time is O of n log n, rather than O of n squared. The logarithmic factor comes from repeatedly halving the problem, while the n factor reflects the need to process all the elements during the merging.

  26. Michael

    That improvement has a space cost. Bubble sort and selection sort work in place, repeatedly rearranging the existing elements. Merge sort temporarily uses additional space to hold pieces while it sorts and merges them, effectively using more memory in exchange for less time.

  27. Anna

    This illustrates a recurring principle in computer science: time and space are resources that can be traded against each other. An algorithm may use extra memory to run faster, or save memory while doing more work.

  28. Michael

    All of these array-based algorithms depend on contiguous memory. An array is excellent for random access, but it creates a difficult growth problem. When a program asks the operating system for six adjacent bytes, the neighboring locations may later be assigned to something else.

  29. Anna

    If a seventh value arrives and the next byte is occupied, the array cannot simply grow in place. The program might have to request a larger block somewhere else and move all the existing values there. Moving those values takes time.

  30. Michael

    The alternative is to reserve extra space in advance, perhaps asking for seven, sixteen, or one hundred positions. That provides room to grow, but unused memory is wasteful and unavailable for other uses. So arrays offer fast access, but the programmer must make decisions about capacity.

  31. Anna

    A linked list addresses the growth problem differently. Its values do not have to be next to one another in memory. Each value is stored in a node, and each node also stores the address of the next node.

  32. Michael

    Those addresses are often represented conceptually as arrows, or pointers. If the values 4, 8, 15, 16, 23, 42, and 50 are scattered through memory, each node can store its value plus the address of the next node. The final node stores a special indication that there is no next node.

  33. Anna

    This makes insertion and removal flexible. To add a node, we can place it wherever there is available memory and update a pointer. To remove one, we can change the preceding node's pointer so it skips over the removed node.

  34. Michael

    But linked lists give up random access. We remember where the first node is, then follow the pointers one at a time. To reach the middle or the end, we may need to traverse many nodes, so searching can take linear time. Linked lists also require extra space because every node stores both its data and pointer information.

  35. Anna

    A binary search tree tries to combine dynamic growth with efficient searching. Its nodes can be located anywhere in memory and connected using pointers, but each node has at most two children: a left child and a right child.

  36. Michael

    The defining ordering rule is that values in the left subtree are smaller than the node, and values in the right subtree are larger. If 16 is the root, 8 can be on the left and 42 on the right. Then 15 belongs to the right of 8, while 23 belongs to the left of 42 and 50 to its right.

  37. Anna

    To search for 15, start at 16. Since 15 is smaller, go left to 8. Since 15 is larger than 8, go right and find 15. This can take logarithmic time, O of log n, when the tree stays reasonably balanced.

  38. Michael

    Balance is essential. If values are inserted in an unfortunate order, the tree can become long and string-like, effectively turning into a linked list and losing its logarithmic performance. Some tree designs use additional code to rebalance themselves and keep the height small.

  39. Anna

    Trees also use more space than arrays because each node may need pointers for two children. Again, the trade-off is clear: additional memory can provide dynamic structure and potentially faster searching.

  40. Michael

    A hash table aims for approximately constant-time access by combining an array with a function that maps keys to positions. Suppose the keys are names. We could use the first letter as a simple hash: Alice goes to the A position, Bob to B, and David to D.

  41. Anna

    Computers can convert characters to numeric codes using systems such as ASCII or Unicode. For capital letters in ASCII, subtracting the code for A from the code for a name's first letter can produce an array index. That takes a fixed number of steps, independent of how many total names are stored.

  42. Michael

    The problem is collisions: different names can produce the same index. David and Doug both begin with D, for example. One solution is for each array position to point to a linked list containing all the names assigned to that bucket.

  43. Anna

    A good hash function distributes keys across many buckets, keeping those lists short. A function that looks only at the first letter might perform badly if many names begin with the same letter. Using more information, such as the first two letters, can reduce collisions, although collisions can never necessarily be ruled out.

  44. Michael

    That is why hash-table performance is described as approximately or ideally constant time, not an absolute guarantee in every case. With few collisions, access and insertion are close to constant time. In a worst-case collision pattern, the structure can degrade toward a long linked list and linear time.

  45. Anna

    At a higher level, programming languages build familiar data types and structures on these memory principles. Values such as booleans, floating-point numbers, integers, and strings occupy particular arrangements of bits and bytes. A float has limited precision partly because the program allocates a fixed number of bits for its representation.

  46. Michael

    Python's dictionary is an abstraction built around the hash-table idea: keys are used to retrieve associated values. A Python list provides the idea of an array with added dynamism, allowing it to grow and shrink through lower-level memory management. Sets represent collections without duplicates, tuples can group values such as an x and y coordinate, and ranges represent sequences of values.

  47. Anna

    The important lesson is that data structures are not merely storage containers. They determine what operations are convenient and how efficiently algorithms can perform them. Arrays support direct indexed access, linked lists support flexible insertion and removal, binary search trees support ordered dynamic searching, and hash tables can provide near-constant-time access when their hashing is effective.

  48. Michael

    And every choice involves trade-offs among time, space, flexibility, and sometimes memory cost. The best performance often comes from matching the data structure to the problem: sorted contiguous data for binary search, extra space for merge sort, pointers for dynamic structures, or hashing for fast key-based lookup.

  49. Anna

    So algorithms and data structures work together. An algorithm can be correct but inefficient if the data is arranged poorly, while a suitable data structure can make the same kind of problem dramatically faster. That combination of organization and procedure is one of the central ideas behind efficient programs, databases, and software systems.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent