1. Home
  2. Explore
  3. Computer Science
  4. Week 3: Algorithms

Study methods

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

Week 3: Algorithms

Transcript

[MUSIC PLAYING]

DAVID MALAN: All right, this is CS50, and this is already week 3, our fourth. And this week's focus is going to be pretty much entirely on algorithms, which is exactly where we started the course, recall back in week 0. But in one of those algorithms, recall, involved a certain phone book, first physically and then virtually and, indeed, in a phone book, of course, you have all of these names and all of these numbers, presumably alphabetized by first name or last name. And we looked for someone back then, namely John Harvard, some of whom-- and some of you might have called or texted even perhaps that number at the time. But recall that among the goals of having that whole conversation about finding John Harvard or anyone in a phone book, digital or otherwise, was to talk about just how good the algorithm was. It sort of went without saying in week 0 that the algorithm has to be correct. Otherwise, what's the point of writing it or implementing it

in the first place. But we also talked about design and can you make a better algorithm by thinking a little harder about it, maybe harnessing some of your intuition, and actually speeding things up as we discussed? So the first algorithm, recall in week 0, one page at a time was perfectly correct, but super slow. And we described its slope with this straight line here. And if that phone book had, say, n pages, where n just means number, it was a one-to-one relationship because if you add more pages, you need more steps. The second algorithm, recall, where I went two pages at a time was twice as fast, so surely better. Potentially incorrect, though, if John Harvard got sandwiched between two pages, but we proposed to solve that by just doubling back one page if need be if you pass the J section, maybe hit the K section, and therefore, need to go back at least one page. And that algorithm was fundamentally better.

Its line was fundamentally lower than the first algorithm's one because, of course, it takes half as much time to implement that second algorithm plus one extra step just to double back. But the third and final algorithm in our very first week together, recall, was that so-called divide and conquer. And today, we'll give it a name again, binary search-- bi- implying two because we were dividing in half, in half, in half, again and again. And we got this fundamentally different shape, whereby even if we double the size of the phone book next year-- I proposed maybe Cambridge and Alston here in Massachusetts merging together. So you go from 1,000 pages to 2,000 pages. One of you observed that that's not a big deal because you need just one more tear of the phone book to actually take a big bite out of that problem and go from 2,000 to 1,000, then to 500, then to 250, and so forth pages in the phone book. So this week is really going to be about implementing algorithms, not

only correctly but also efficiently and really focusing on design. There won't be much new syntax in C. We'll give you a couple of building blocks that solve concrete problems. But this week is really about taking a breather after the past two weeks of fairly new, fairly intensive C code and just solve some new, more sophisticated problems together. So let's consider how we can go about solving problems involving data. Case in point, phone books are a good example insofar as they represent a decent-sized data set that ideally is, in fact, sorted alphabetically or otherwise. And in the real world, we are searching for-- we are sorting information all of the time. Odds are, within the past hour or so, all of us have used Google or some search engine in some form. How does Google get us search results like that? Well, they've probably used some kind of very clever layout in their servers' memory to get us answers really quickly.

So we'll begin to think about, especially when data gets big, how we can use this kind of hardware but use-- and on top of which, we'll write software to solve actual problems. So here, again, is a little black chip on top of what's otherwise called a circuit board or a logic board inside of our Macs, PCs, and phones. If, though, we abstract this away and just assume that if this big chip here represents like one gigabyte of memory, 1 billion bytes or eight billion bits, well surely we can just arbitrarily but consistently number them, like this is byte 0, this is byte 1, byte 2, dot, dot, dot, byte 1 billion all the way down here in the bottom. So we can address our memory in this way. So let's forget about the actual hardware there and now talk about what really is going on inside of the computer's memory, borrowing ideas from last week. So if this is just a canvas of memory, each of whose squares

represents 1 byte of memory, how can we go about laying out information, be it names or numbers or web pages or anything else? Well, recall that we divvied this memory up into chunks last time, and we call this an array. And what was key about an array was that it was just a bunch of values back to back to back in memory, so-called contiguous. And it wasn't a huge deal last week that these things were contiguous in memory back to back to back. But this week, it's actually going to really matter because of that layout and because of last week's, week 2, that we can actually solve problems efficiently in this week 3. So, for instance, here are a whole bunch of numbers, and these numbers are stored in an array. And this array is of size 7, it would seem, because there's 1, 2, 3, 4, 5, 6, 7 numbers in this here array. And, of course, you and I can see all of these numbers at a glance, with a bird's eye view.

But the catch is that computers technically can only look at one location in memory at a time. Now that's a bit of a white lie because computers are getting so darn sophisticated nowadays that different types, fancier computers can maybe do multiple things at a time. But for our model, today, we'll assume that a computer can indeed only look at one location at a time. So, for instance, if you're searching for the number 50 among all of these values here, well, all of us in a split second can kind of spot it over there, third from the right. But a computer is going to have to look for it a little more methodically, more algorithmically, if you will, step by step, in order to solve that problem. So a good mental model to have when it comes to what's going on inside of your computer is that these numbers are, yes, in an array, but they might as well be locked up behind closed doors, whereby in order to see each of those values and find one of them,

the computer is metaphorically going to have to open up each of those doors one at a time, looking, looking, looking for the number that we actually care about. Now it turns out we can treat this array of closed doors, gym lockers, if you will, much like an array. So this might be location 0, location 1, location 2, dot, dot, dot, location 6. To be clear, there's seven doors total, but as always, if you start counting from 0, it's n minus 1, which refers to the rightmost or the last door, so 6 instead of 7. But there's indeed a total of seven doors here. Just for parity with the lockers we were able to buy online, you might as well think of these as red doors, behind which are all of those numbers. So if the goal at hand now is to mimic what's going on inside of a computer, I bet we could figure out how to find information among these doors. And this is just a problem to be solved in the world of computing.

This is the problem of searching, not surprisingly. And what does that really mean? Well, if we go back again to week 0, where this is computer science, this is problem solving, what's the input to this problem? Well, we have an array of seven doors that might as well be locked up behind these doors. And we want to get as output a Boolean value, like true or false. Yes, the number 50 is here or no, it is not. So true or false respectively will get the job done. And inside of this, of course, is going to be, as always, some kind of algorithm, step by step instructions for actually solving this problem. So how, then, would a computer concretely go about searching for numbers behind this door? Well, maybe just for fun, we went ahead here and printed out some monopoly money, some large versions thereof. And suppose we want to find very specifically the number or the dollar amount 50 behind one of these doors.

Could we get maybe one, maybe two volunteers to come on up? I saw your hand go up first, second on the end there. And let me look over here-- over here, behind the camera, number two, come on down. OK, come on over. Maybe a round of applause to break the ice for these two. [APPLAUSE] Come on up. And we've got two algorithms ahead of you. But come on over here. If you want to introduce yourself to the world-- maybe a quick something about each of you. STUDENT: Hi, I'm Jonathan. I'm a sophomore in Cabot House studying economics. DAVID MALAN: Wonderful. Nice to meet you. And-- STUDENT: Hi, I'm Claire. I'm a junior in Elliott, studying economics and TDM. DAVID MALAN: All right, nice, wonderful. Glad to have you both here. So behind you are seven doors. And which of you would like to go first? OK, so first, if you want to come on over here, behind these seven doors are now dollar amounts, namely all of the available monopoly dollar amounts.

And if you want, we want you to find the number 50. You can go about this in a bunch of ways. Like, you could go about just opening random doors, but that's not necessarily very repeatable. That's not very algorithmic step, by step. So let me propose that you do something super simple. Start at the left door and work your way to the right. And just so everyone knows what's going on, go ahead and show the world what number you've pulled out of each of these lockers. And the first locker is-- STUDENT: 20. DAVID MALAN: 20. That is correct-- not 50. STUDENT: 500. DAVID MALAN: So incorrect.

STUDENT: 10. DAVID MALAN: 10. Not correct. STUDENT: 5. DAVID MALAN: Not correct. STUDENT: 100. DAVID MALAN: 100. Not correct. STUDENT: 1. DAVID MALAN: 1. Not correct. Hopefully last door-- and round of applause, if we could, for finding the number. [APPLAUSE] So if you don't mind, before we transition to a better algorithm-- because, frankly, that was pretty bad-- but it wasn't incorrect in the sense that he was doing anything wrong. He sort of just had some bad luck. And, frankly, if I hadn't sort of led him to that path from left to right, I could have proposed more cleverly that you maybe start from the right and then, boom, the problem would have been solved. But, in general, if data isn't necessarily cleanly laid out by us humans in this very manipulative approach-- like maybe it's going to be at the beginning of the array. Maybe it's going to be at the end of the array-- you really don't know. So you might as well have one methodical approach, step by step, and just do it again and again.

So I think, even though that felt increasingly awkward because you didn't find the 50 till the end, that was kind of as good as you could have done in general. And let me propose, before we try a second algorithm, if we take a look at some pseudocode here, I daresay what you implemented, with my sort of encouragement, was something called linear search-- literally walking in a line from left to right. And if we take the fun out of searching for money behind doors, we can make this more algorithmic with pseudocode-- English-like code, but written in very terse language. He did, for each door from left to right, if 50 is behind the door, ideally, then you would have returned true. And that's when everyone applauded, of course. Else, if not, you might return false at the very end of this code. So we got lucky. 50 was there. But if you hadn't, you might have decreed, oh, no, there's no 50, so I returned false.

But notice the indentation here, just to highlight a key detail. I'm only returning false once I'm done with that loop. For instance, if I had poorly implemented this pseudocode like this, indenting that return false and only doing it conditionally if 50 is not behind the door-- I know we're putting you on the spot here, but do you want to conjecture why this would be bad if you spot the mistake? STUDENT: If you put false right after else, that means once we search the first door and we don't find 50, it'll just return false and the program will finish. DAVID MALAN: Exactly. So this code would indeed be a bad implementation-- incorrect because only if the 50 is behind the first door would it ever work correctly. We would otherwise bail out and return false prematurely. So this version here is indeed correct. But can we do better. Well, the numbers that were behind the doors for you, were they in any particular order?

STUDENT: No, they were randomized. DAVID MALAN: So we kind of set you up for failure in that sense. So if you don't mind, let's go ahead and pass the mic over. And secretly, behind me a moment ago, Yuliia was kindly sorting all of those same dollar amounts behind the doors. And the question at hand now for you is going to be find the number 50. But let's do this a bit like the phone book in week 0, where let's start in the middle. And if you recall from week 0, then let's go left or right accordingly. So what's behind the middle door? And we have-- STUDENT: It's 20. DAVID MALAN: 20, so not correct. But what do we now know? 50 is in which direction? STUDENT: To the right. DAVID MALAN: All right, so to the right-- so go to the middle of the right. So that leaves you with these three lockers in that middle door now. STUDENT: It's 100. DAVID MALAN: 100, so too big. So what do you now know? STUDENT: It's going to be to the left. DAVID MALAN: Has to be, logically, if it's there at all, in between those two.

And now we get your round of applause much faster than before. [APPLAUSE] So this, then, if I can step over here before we give you a parting gift, this is where we left things off a moment ago. And in linear search, line from left to right, we checked each door. But just to make things a little geekier now and a bit more quantitative in nature, that really is the same thing as slapping numbers on this problem, whereby the first door we're going to call 0. The last door, we're going to call n minus 1 if we start to treat these lockers not as physical objects, but as arrays instead. So, in that same spirit, let me propose that when we found the number 50 this time, we took a fundamentally different approach, just like week 0, when we did divide and conquer, a.k.a. binary search-- binary implying we split the problem in 2 and 2 and 2, by going left or right each time. And the pseudocode that you might have arguably just implemented

looks a little something like this. If 50 is behind the middle door, well, we got lucky, and we can simply return true right away. But if it's not, if 50 is less than the value at the middle door, we could have gone left, even though you didn't need to. Else, if 50 is greater than that of the middle door, we could search right, and you did do that. But there's a fourth scenario here, and we talked a bit about this in week 0. Do you spot what other scenario I might want to consider? If it's either in the middle or to the left or to the right, what else might happen?

So what else might happen? It was that fourth scenario. Yeah? STUDENT: [INAUDIBLE] DAVID MALAN: So it might not be there at all. I could have really set you up for failure by not putting the 50 there. And in code, though, we need to handle that because I conjectured in week 0, when you don't handle all possible scenarios, that's when the computer crashes or freezes or just something goes awry. So if there are no doors left, you sort of run out of possibilities. Logically, we had better make sure we return false. So before we give you both maybe one final round of applause, wonderfully, Monopoly makes its own Harvard edition for Cambridge. So we have a nice parting gift for both of you today. Thank you both for coming on up. [APPLAUSE] All right, so just to now make that algorithm a bit more quantitative, instead of just saying middle, middle, middle, let's use a bit of array syntax here now too.

So this is the same exact pseudocode for that algorithm binary search. And so the first condition is the same. If no door is left, just return false. But if 50 is behind doors bracket middle-- and, again, I'm sort of stealing some syntax from last week, where we introduced square brackets for arrays, but I'm still using pseudocode. So this isn't C per se, but by doors, I mean the array known as doors. Bracket middle I mean whatever the middle index is, go there. If you found it behind the doors bracket middle, return true. Else, as we enacted a moment ago, if 50 is less than the middle door, then go ahead and search what? Well, instead of saying search to the left and search to the right, let's make this, again, more precise today. Search the array of doors from location 0 all the way through location middle minus 1. So what do I mean by that? Here was the middle door. And even though this is not what we did a moment ago, if we were to go left,

here's bracket 0, the first door. Here is middle minus 1 because if this is middle, minus 1 is immediately to the left. And this is why this algorithm would indeed have a searching the left half. Equivalently, if 50 is greater than doors bracket middle, then search doors middle plus 1 through doors n minus 1. Well, the end of an array, if 0 indexed-- that is, you start counting at 0-- this is always n minus 1. If this is middle, middle plus 1 is here. And this is exactly what you just did, searching the right half of those doors. So we have this translation then from of the intuitive pseudocode from week 0 into now the more technical expression of arrays and array syntax here this week. And that's something now we'll begin to build on over the course of writing and implementing some of these problems here today. So if we now have algorithms that both solve the same problem, just like in week 0, which of those algorithms

was better-- the first one, which we called linear search, or the second one, which we called binary search? They're both correct, I would claim. So which is better? Which is better design? Two. And why do you say that? STUDENT: It's more efficient. DAVID MALAN: OK, so 2 is more efficient insofar as the second algorithm, if I'm thinking back, only took three steps. You only had to open up three of the doors, whereas the first algorithm linear search actually took as many as seven steps. And, in fact, we'll see some math underlying this. But it would be nice now if we could really compare the design of the efficiency of algorithms a little more rigorously than just saying one is better than the other. Let's see if we can slap not some numbers on it but maybe just some very simple arithmetic or algebraic formulas that allow us to compare two algorithms so that in the real world and in problem sets and in projects in the future,

you can make a more quantitative claim as to which approach is indeed better. So when we talk about running time, we literally mean that-- like, how much time does it take for a program to run. But we don't necessarily count in terms of seconds or ticks of a clock more generally. Instead, we'll try to count the number of operations that an algorithm takes. So, for instance, this was a way of analyzing the running time of three algorithms way back in week 0. And I did introduce a bit of jargon, whereby I was using expressions like n to represent n pages or n divided by 2 to represent half as many pages. And even though I waved my hand at week 0, log base 2 of n is mathematically how you would represent the idea of dividing something in half in half in half if you start with n pages. So those are three formulas. But it turns out that at least two of these algorithms from week 0, they're pretty darn similar to one another.

Indeed, literally two of these are straight lines, even though the slope is slightly different. The other one is fundamentally curved and, therefore, different and, indeed, we saw better. But let's get out of the business of worrying about maybe constant values, like dividing by 2. We really want to care about when algorithms are sort of fundamentally better than one or the other. So case in point, here are those same two algorithms from week 0. This was turning one page at a time. This was turning two pages at a time. Honestly, if I wanted to speed things up by a factor of 2, why don't I just use a faster Mac, a faster PC? Nowadays, I could literally wait one year, and next year's computer will be practically twice as fast, it would seem, than the first. And so if we start to try to compare the efficiency of algorithms, it would be nice if they're sort of resilient, those comparisons, to what computer you use to run the code.

We want to take a step back and approach things a little more mathematically, but fairly lightweight nonetheless. And so the way a computer scientist typically describes the running time of an algorithm is by using a capital O as a letter and using it to imply on the order of this many steps. And I actually keep saying as a turn of phrase, wave my hand at a problem. This is the mathematical equivalent of I don't really care about the very precise mathematical formula. It is roughly on the order of this fast or this slow. So what this means is that if you want to describe the running time of this algorithm, this one, or this one, syntactically, you literally write on a piece of paper or an essay or the like, big O, and then, in parentheses, a little mathematical formula that describes how the running time relates to the size of the problem, just like this xy grid. But it turns out, and I'll claim, we rarely

care about denominators if they're just constants, like 2 or 3 or 4. All we care about really is the highest order term. So whatever the biggest mathematical component is in the expression, the one that really matters as n gets big, that's the one we care about because, frankly, if n is, like, 2 billion pages, 2 billion in size, well, 1 billion still feels pretty darn slow. If it's going to take that many steps, they might as well be just as slow as each other. But this one here, similarly, if you remember your logarithms, even the base doesn't matter because you can actually multiply 1 logarithm by a constant to change the base. And so here, too, we're going to get rid of the specific constant like 2. And here then is how we would describe the running time. And, in fact, if you zoom out in your mind's eye and assume that the y-axis is bigger and the x-axis is bigger, if you keep zooming out, zooming out, zooming out,

these two lines are actually going to pretty much look the same once you've zoomed out far enough. And that's what I mean by they're essentially themselves algorithmically the same. As n gets big, big, big, these might as well be the same algorithms, but this one is clearly not. And we claimed in week 0 that this one was better. I claim again today that this one is better. And now we'll begin to slap some formulas on the evaluation of these algorithms so that we have a better sense of what algorithm is better than someone else's. And, indeed, in the real world, when you talk about what makes someone a good programmer, what makes someone a good engineer is having an intuitive sense, with practice and with time, of how you should write your code so that it maybe has a better running time than some other algorithm. Because when you start working at Google or Microsoft or working in medical data sets or financial data sets

and the data is really big, n is really big, you probably want to be as efficient as possible. So this [INAUDIBLE] capital O is generally called big O notation-- not particularly technical, but that's indeed what it's called. And here, for instance, is a little chart of very common runtimes. You can use any mathematical expression, but almost always, in the context of computing, at least introductory-type algorithms, this is the list of possibilities, even though there's infinitely many more. So among the algorithms we've considered thus far, what is the running time of linear search? Well, it's on the order of n because if there's n doors, like those behind me, in the worst case, consider how many steps might it take me or take you? It will take n steps, specifically 7, but n in the general case. And so big O is very commonly used when you do want to think about the worst case because, honestly, who really cares if you got lucky and the first door you opened

had the number you're looking for? That doesn't really generalize. And that's not a good argument within Google-- well, hey, once in a while, someone will get lucky and we'll really return them a search result quickly. You want the general case to be fast. And so linear search, really in the worst case-- like, which customer is going to be the least happy with our Google code? Linear search describes that-- an upper bound, so to speak, on how many steps it might take. What about, though, best case running times or lower bounds on how fast an algorithm might be? Sorry, I should have not spoiled this. What's the running time of binary search? If the running time of linear search is big O of n, well, the running time of binary search, by contrast, is going to be log base 2 of n or, more generally, log of n. She could have gotten lucky, our volunteer, by just opening the middle door and, voila, maybe 50 was there. It wasn't.

But in the worst case, she only had to look at big O of log n doors in total. And that gave us roughly three doors in this case. What if we want to talk about best case running times, just because it would be nice that, in certain situations, how fast can our code actually run? How good is our algorithm? Well, in computing, computer scientists use a capital omega symbol to represent a lower bound. So big O is upper bound. Big omega is lower bound, and you can use the same kind of mathematical formula. So here's that little cheat sheet again, but with an omega prefix, which again means lower bound. And same question-- in linear search, where you look at the doors left to right, in the best case, how few steps might it take to find a number? I'm seeing just one because we could get lucky, and because we go from left to right, could be that we find the number right away. So that's in big omega of 1, in this case, one step.

Otherwise, how about binary search? What's the lower bound on how quickly we might find a value? Same thing, right, because we could just get lucky because, by starting in the middle, it might happen to be right there. So the lower bound on binary search, too, also happens to be in big O of 1 because we just simply get lucky. What if those two are one and the same? One last piece of Greek symbology here-- capital theta here is used when big O and omega are exactly the same thing, which won't always apply, but sometimes, an algorithm performs at this rate as well as at this rate, and they're one and the same depending on the algorithm itself. So here's a little cheat sheet here. And how about linear search? So linear search, in the best case, takes only one step-- in the worst case, takes as many as n steps. So those are not really one and the same. So theta is really inapplicable here.

And binary search, too, this is sort of inapplicable because in the best case, it might take me one step, hence the big omega of 1. But in the worst case, and it's not even that bad, it might take me big O of log n. So theta doesn't apply here. But we'll keep an eye out today and see if there aren't certain algorithms that we'll look at that might actually have those values being one and the same. And all of this symbology-- and that's it really for definitions for now-- is what's generally called asymptotic notation. It's notation that you use when talking about the running time of algorithms over time. As the input gets larger and larger and larger, how do these algorithms perform? How can you measure their efficiency? Any questions on big O, omega, or anything prior? We'll come back to theta before long. Any questions? Yeah, have in front. STUDENT: [INAUDIBLE] DAVID MALAN: Sorry, say again. STUDENT: [INAUDIBLE]

DAVID MALAN: Is binary search efficient with respect to-- STUDENT: When searching [INAUDIBLE] DAVID MALAN: Oh, really good question-- is binary search efficient when searching random data as was the case with our first set of doors? And, indeed, those numbers were all over the place. They were not sorted from smallest to largest or largest to smallest. So what is the answer to that? Is binary search efficient when the data is random? STUDENT: It doesn't work at all. DAVID MALAN: It doesn't work at all. And so that was the hidden cost of the two algorithms that we acted out. And, literally, I had Yuliia come up and help me. She did more work to enable us to use binary search because only for the second exercise with the lockers was the data actually sorted. So binary search just does not work if the data is random because you would open a door, see a number, like the number 20, and now you would make a decision whether to go left or right based

on the number you've seen. So you simply cannot use binary search when the data is unsorted, a.k.a. random. In that case, then, how do you sort the data-- that's going to be one of the problems we solve ultimately today-- get the data sorted, help Googles of the world, sort their data first so that we can find web pages and other things more quickly. Yeah, in back-- oh, any questions? No? All right, so let's actually translate some of this to a little bit of code here. How can we go about implementing something like linear search? Well, let me do this. Let me go over to VS Code here. Let me propose to create a new program called search.c. So I'm going to do code search.c. And in here, I'm going to use the CS50 library at the top so I can get input. I'm going to use stdio.h so I can print stuff out on the screen. I'm going to use int main(void) because, for today, I don't really care about command line arguments for this particular program.

And let me start with an array of values. Suppose I want to implement, in code, the idea of these lockers containing those random values initially and implement, in C, the very first algorithm we enacted with our volunteers, which was searching from left to right. Well, it turns out, in C, I can create an array, recall, by saying I want integers, I want the array to be called numbers, and then, inside of square brackets, I can specify how many elements I want. Maybe I want three, like last week. But, in this case, I think I want seven this week to represent each of these lockers. But it turns out, you can initialize an array. Without even using get_int or the like, you can just specify an empty square brackets that whole array should equal the following inside of curly braces. So this is one new use of curly braces, but it's a handy trick when you want to create an array that has specific values, like 20, 500, 10, 5, 100, 1, and 50, which

just happens to be the exact order in which the dollar amounts previously were behind those lockers. So what does this line 6 do at the moment? It creates for me an array of size 7 and initializes it to that sequence of values from left to right. It is not strictly necessary to bother putting 7 there, and it's probably best not to because the computer, specifically the compiler, will figure out how big the array should be based on what you typed inside of those curly braces, and you're just inviting a mistake if you put a number over here that's supposed to match the total over here. At some point, you're probably going to error. So if that gives me then an array of size 7. Let me go ahead and ask the user, what number do you want to search for, much like I verbalized before? So int n equals get_int, and I'll prompt the human for a number as with this kind of prompt. How do I now implement linear search?

Well, based on the constructs we explored in week 0 and week 1, we had conditionals and loops and variables and Boolean expressions and the like. What is probably the feature of a programming language that we're going to need to search from left to right to implement linear search? STUDENT: A for loop. DAVID MALAN: A for loop, probably, or a while loop, but a loop in general. Why? Because I could use, like, seven conditionals, and I could say, if the numbers bracket 0 equals equals this value, then return true. Else, if numbers bracket 1 equals equals this number, then return true. But that's not very general purpose. If we're going to have all of these conditionals, let's just have one that asks the same question by just changing some variable. And a for loop is often the paradigm. So for int i equals 0, i is less than 7, i plus plus, and this code alone sort of sets me up to implement

what our first volunteer did from left to right with the lockers. What's the question I want to ask? Well, does the array of numbers at the current location i equal equal the number n that we're actually looking for? So does the number behind the first door, second door, third door actually equal 50, for instance, or whatever's typed in? And, if so, let's go ahead and print out something clear, like "Found" backslash n-- else, I don't think I want to do this-- printf "Not found."

So let me, for a moment, sort of poorly implement this. What have I done wrong with this code? Yeah, in the back. STUDENT: [INAUDIBLE] DAVID MALAN: Yeah, I don't want the-- I want the if inside for loop but not the else inside for loop. Why? Because that would be the equivalent of starting at i equals 0, opening the door, and then concluding I have found or not found the number without even allowing us a chance to keep going because we're going to spit out, unilaterally, "Not found," even though we just haven't found it yet. So I don't think I want to do that. But I think what I can do, for instance, is as per the slide a bit ago, if I, at the end of my loop, get all this way, then I think I can print not found. But I think, logically, even this might be imperfect. So let me go ahead here and do make search Enter. Seems to have compiled OK, so no syntax errors. Dot slash search Enter-- what number do I want to search for?

I'm going to go ahead type 50 and hit Enter. And still, I have a logical bug. It's saying "Found" but also "Not found." Why? Even though I moved that line of code outside the loop, which is correct, but there's still something wrong here. Yeah? STUDENT: [INAUDIBLE] DAVID MALAN: Yeah, the iteration still ends up leading us to this final line. Why? Because we're going to go all the way from 0 to the end of the array again and again and again, hopefully printing out found when we find it.

But there's nothing stopping us from then executing line 16 before the program actually ends. But recall, last week, we had a solution to this. Even main can return a value. And even though, in week 1, it was sort of secretly returning the number 0, unbeknownst to us, it turns out, we now had the ability, as of week 2, to explicitly return a value anywhere in main that we want. And the convention, a little paradoxically, is to return 0 upon success, because that means all is well, and then return anything other than 0, like a positive integer, if anything has gone wrong. And we use positive integers because it could be this thing that goes wrong, this thing, this other thing. Lots more can go wrong than can go right when writing code. So I think what I could do here is, after printing "Found," I could return 0 to signal success, even though the human's not going to see anything different. And down here, I could actually return 1 to signify failure.

And recall, with the little command trick, I could do dollar sign, question mark, and actually see what that value is. But, for our purposes, what we really care about is that main returns when we are done solving this problem, either inside of the loop or ultimately outside. So let me try this again-- make search dot slash search. Let's search for, again, the number 50, Enter, and indeed, it is "Found" and only "Found." Let's do this again-- dot slash search. Let's search for the number 2, which is not in that array. And I should see and only see "Not found" in this case. So this then would be the code for linear search. Any questions on what we just did here? Yeah? STUDENT: [INAUDIBLE] DAVID MALAN: A really good question-- what if we don't initialize the array? Honestly, in programming, a very good answer to that question is just try it out and see what happens. So let me create an array of size 7 with no values inside of it.

Let me reopen my terminal window, do make search, and the compiler doesn't seem to mind that. If I go ahead and now do dot slash search, Enter, I'll be prompted for a number. I'm going to presume to search for 50, even though I don't know what's in there. Enter, and at least it was not found here. Let me go ahead and try again. Let me search for the number 2-- not actually found. Search for the number 1-- not actually found. And I can poke around all day long, but it turns out I'm probably just getting lucky here. Why? Well, this loop, no matter what, is going to check seven locations. But I have not put anything in any of those seven locations. But recall, from last week, we sometimes saw those garbage values, sort of remnants of memory that, of course, exist, but maybe had been used for some other value previously. At the moment, I think I'm just getting lucky that among the first seven locations in the computer's memory,

I just didn't end up with a garbage value 50 or 2 or 1. But if we played this game for a while, I bet I could come up with a number that actually works. And let's see, at the risk of a demo not going according to plan, let me do dot slash search. Let's search for 0-- still not there. Let's search for 3, 4-- we're going to have to do this all day long to actually find the values. There's four billion possibilities, but at some point, we would get lucky, and it would say "Found," but only by chance. So, in short, do not do that, since it is wrong. Other questions on the code that we've just written? So let's transition then to maybe a better version of this. What if the numbers are actually sorted? And, frankly, what if they're not actually numbers at all? Let me go back into this code. Let me throw away the contents of main, and let's do something maybe now with strings instead, just so it's more like searching an actual phonebook.

So I'm going to create an array of strings called strings for lack of a better name, and much like a certain game with which you might now be familiar, we might have a string for battleship and boot and cannon and iron and thimble and top hat, though this does vary by country based on which version of Monopoly you actually have. Then let's go ahead and prompt the user for a string s, using get_string, and ask them for a string to search for. And then let's do a for loop again for int i equals 0, i less than 1, 2, 3, 4, 5, 6 values. I'm hardcoding 6, and I don't like that, but we'll come back to that idea in general of figuring out what the length of that array might be. But for now, I'm just going to hardcode it. But that's not, indeed, good practice-- i plus plus inside of the for loop. Now let me go ahead and do this. If the i-th string, or the strings at location i, equals equals s,

then let me go ahead and print out, as before, "Found." Let me not make the same mistake as before. So let me immediately return 0 to signal success. But if we don't find it anywhere in that array, let's go ahead and print out "Not found." And then let's go ahead and return 1, just as before. So the only thing that's different now is I'm using strings instead of integers, but I'm otherwise looking for the i-th string that might very well have the same value as s, what I have typed in. Let me go ahead and open my terminal again, run make search again-- so far, so good. Dot slash search-- let's search for maybe the thimble-- Enter. Huh, it's not found. All right, maybe it's too far away. Let's search for again-- battleship Enter. Not found. How about the top hat, Enter. Not found. And I could do this three more times, but I'll claim that it's never going to find any of these strings. Does anyone have a suspicion as to why? Or how we might solve--

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent