1. Home
  2. Explore
  3. Computer Science
  4. Searching and Sorting Algorithms

Study methods

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

Searching and Sorting Algorithms

Transcript

All right, this is CS50. This is week 3, and this was an artist's rendition of what various sorting algorithms look and sound like. Recall from week 0 that an algorithm is just step by step instructions for solving some problem to sort information, as in the real world just means to order it from like smallest to largest or alphabetically or some other heuristic. And it's among the algorithms that we're going to focus on today in addition to searching, which of course is looking for. Information as we did in week 02. Among the goals for today are to give you a sense of certain computer science building blocks like there's a lot of canonical algorithms out there that most anyone who studied computer science would know, anyone who leads a tech interview would ask. But more importantly, the goal is to give you different mental models for and methodologies for actually solving problems by giving you a sense of how these,

uh, real world algorithms can be translated to actual computers. You and I can control. We thought we'd begin today with an actual algorithm for sort of taking attendance. We of course do this with scanners outside, but we can do it old school whereby I just use my hand or my mind and start doing 123456789, 1011, 12, and so forth. That's going to take quite a few steps because I've got to point at and recite a number for everyone in the room so I could kind of do what my like grade school teachers taught me, which is count by 2s, which would seem to be faster. So like 2468, 1012, 1416, 1820, and clearly that sounds and is actually faster, but I think with a little more intuition and a little more thought back to week zero, I dare say we could actually do much better than that. So if you won't mind, I'd like you to humor us by all standing up in place and think of the number one, if you could, and join us in this here algorithm. So stand up in place

and think of the number 1. So at this point in the story, everyone should be thinking of the number 1. Step 2 of this algorithm for you is going to be this pair off with someone standing, add their number to yours, and remember the sum. Go OK. At this point in the story, everyone, except maybe one lone person if we've got an odd number of people in the room, is thinking of what number? 2, OK, so next step, one of you in each pair should sit down.

OK. Good. Never seen some people sit down so fast. So, those of you who are still standing, the algorithm's still going. So the next step for those of you still standing is this, if still standing, go back to step 2. Ergo repeat or loop if you could. Um And notice if you've gone back to step 2, that leads you to step 3, that leads some of you to step 4, which leads you back to step 2. So this is a loop.

Keep going. If still standing, pair off with someone else, still standing, add together, and then one of you sit down. So with each passing second, more and more people should be sitting down. And fewer and fewer are standing. OK. Almost everyone is sitting down. You're getting farther and farther away from each other. That's OK. I can help with some of the math at the end here. All right. I see a few of you still standing, so I'll help out and I'll I'll join you together. So I see you in the middle here. What's your number?

32. OK, go ahead and sit down and I'll pair you off with what's your number? 20. OK, you can go ahead and sit down. Uh, who's still Then you're still standing. 27? OK, you can sit down. You guys are still adding together, who's gonna stay standing? OK, what's your number? The worst part is doing like arithmetic across a crowded room, but 27 also? 47. OK, you can sit down. Is anyone still standing? Yeah. Nice, 15. OK, you can sit down. Anyone still standing?

OK, so all I've done is sort of automate the process of pairing people up at the end here. When I hit enter, we should hopefully see, oh, the numbers are a little, what's going on there? There we go. When I hit enter, we'll add together all of the numbers that were left. And if you think about the algorithm that we just executed, each of you started with the number 1 and then half of you handed off your number. Then half of you handed off your number, then half of you handed off your number. So theoretically all of these ones with which we started should be aggregated into the final count, which if this room weren't so big, would just be in one person's mind, and they would have declared what the total number of people in the room is. I'm going to speed that up by hitting enter on the keyboard, and if your execution of this algorithm is correct, there should be. 141 people in the room. According to our old school human though, Kelly, who did this manually one at a time,

the total number of people in the room, according to Kelly, if you want to come on up and shouted into the microphone is of course going to be, I don't know, something around 160, I think 160, so not quite the same. OK, but that's pretty good. OK, round of applause for your, your accuracy. OK, so ideally counting one at a time would have been perfectly correct. So we're only off by a little bit. Now, presumably that's just because of some bugs in execution of the algorithm, maybe some mental math didn't quite go according to plan, but theoretically your third and final algorithm wherein you all participated, should have been much faster than my algorithm or Kelly's algorithm, whether or not we were counting one at a time or two at a time. Why?

We'll think back to week zero when we did the whole phone book example, which was especially fast in it. Final form because we were dividing and conquering, tearing half of the problem away, half of the problem away. And even though it's hard to see in a room like this, it stands to reason that when all of you were standing up, we took a big bite out of the first problem and half of you sat down, half of you sat down, half of you sat down, and theoretically there would have been if you were closer in space, one single person with the final count. So let's see if we can analyze this just a little bit by considering We did. So here's that same algorithm. He recall is how we motivated Week zero's demonstration of the phonebook in either digital form, as you might see in an iPhone or Android device, looking for someone, for instance, like John Harvard who might be at the beginning, middle, or end of said phonebook,

but we analyzed that algorithm just as we can now this one. So in my very first verbalized algorithm, 1234, you could draw that as a straight line because the relationship between the number of people in the room and the of time it takes is linear. It's a straight line with each additional person in the room. It takes me one more step. So if you think to sort of high school math, there's sort of a slope of one there. And so this N number denoting number of people in the room is indeed a straight line. And on the x axis, as in week 0, we have the size of the problem in people and the time to solve in steps or seconds or whatever your unit of measure is. If and when I started counting 2 at a time, 2468, 10. And so forth. That still is a straight line because I'm taking two bytes consistently out of the problem until maybe the very end where there's just 1 person left, but it's still a straight line,

but it's strictly faster. No matter the size of the problem, if you sort of draw a line vertically, you'll see that you hit the yellow line well before you hit the red line because it's moving essentially twice as fast. But that third and final algorithm, even though in reality it felt like it took a while and I had to kind of bring us to the exciting conclusion by doing some of the math. That looked much more like our 3rd and final phone book example because if you think about it from an opposite perspective, suppose there were twice as many people in the room. Well, it would have taken you all theoretically just one more step. You know, granted one more loop and there might be some substeps in there if you will, but it's really just fundamentally one more step. If the number of people in the room quadrupled, 4 times as many people, well, that's 2 more steps. equivalently,

the amount of time it takes to solve the Attendance problem using that 3rd and final algorithm grows very slowly because it takes a huge number of more people in the room before you even begin to feel the impacts of that growth. And so today indeed, as we talk about not only the correctness of algorithms, we're going to talk about the design of algorithms as well, just as we have code because the smarter you are with your design, the more efficient your algorithms ultimately are going to be and the slow. Where their cost is going to grow and by cost I mean time like here maybe it's money, maybe it's the amount of storage space that you need. Any limited resource is something that we can ultimately measure, and we're not going to do it very precisely. Indeed, we're going to use some broad strokes and some standard mechanisms for describing ultimately the running time,

the amount of time it takes for an algorithm or in turn code to actually run. So how can we do this? Well, last week we're called, we set the stage. for talking about something called arrays which were the simplest of data structures inside of a computer where you just take the memory in your computer and you break it up into chunks and you can store a bunch of integers, a bunch of strings, whatever, back to back to back to back, and that's the key characteristic for an array. It is a chunk of memory wherein all of the values they're in are back to back to back, so right next to each other in memory. So we drew this fairly abstractly by drawing a grid like this and I said, Well, maybe this is byte 0 and this is by. 1 billion, whatever the total amount of memory is that you have, we zoomed in and looked at a little something like this a canvas of memory. We talked about what and where you can put things,

but today let's just assume that we want 1234567 chunks of memory for the moment, and inside of them we might put something like these numbers here. Well, the interesting thing about computers is that even though if I were to ask you all find the number 50 in this array, I mean, our eyes quickly. See where it is because we sort of have this bird's eye view of the whole screen and it's obvious where 50 is, but the catch with computers and with code that we write is that really these arrays, these chunks of memory, are equivalent to a whole bunch of closed doors and the computer can't just have this bird's eye view of everything. If the computer wants to see what value is at a certain location, it has to do the metaphorical equivalent of going to that location, opening the door, and looking. Then closing it and moving on to the next. That is to say, a computer can only look at or access one value at a time. Now that's in the simplest form.

You can build fancier computers that theoretically can do more than that, but all of the code we write generally is going to assume that model. You can't just see everything at once. You have to go to each location in these here lockers, if you will. Starting today too, when we talk about the locations in memory, we're going to use our old zero indexing vernacular. That is to say we start counting from 0 instead of 1. So this will be locker 0, locker 1, locker 2, all the way up to locker 6. So just ingrained in your mind that if you hear something like location 6, that's actually implying that there's at least 7 total locations because we started counting at 0. So that's intentional. We don't have in the real world yellow lockers, so we're going to make this metaphor red instead. We do have these lockers here and suppose that within these 7 lockers physically. On stage we've put a whole bunch of money, monopoly money, if you will,

but the goal initially here is going to be to search for some specific denomination of interest and use these physical lockers as a metaphor for what your computer is going to do and what your code ultimately is going to do if we're searching for the solution to a problem like this. The input to the problem at hand is 7 lockers, all of whose doors are metaphorically closed, the output of which we want to be a bull, true or false answer. Yes or no, that number is there or no, it is not. So inside of this black box today is going to be the first of our algorithms, step by step instructions for solving some problem where the problem here is defined among all of these dollar bills, specifically the $50 bill. If we could get two volunteers to come on up who are ideally really good at monopoly. OK, how about over here in front and uh how about let me look a little farther and back. OK, over here, there and back. Come on down. All right,

as these volunteers kindly come down to the stage, we're going to ask them in turn to search for specifically the $50 bill that we've hit in in advance. And if my colleague Kelly could come on up too because we're going to do this twice, once searching in one with one algorithm and a second time with another. Let me go ahead and say hello if you'd like to introduce yourselves to the group. Hey, I'm Jose Garcia. Hi, I'm Caitlin Cow. All right, Jose and Caitlin, nice to meet you both. Come on over and let me go ahead and propose that Jose, um, the first algorithm that I'd like you to do is to find the number 50 and let's keep it simple. Just start from the left and work your way to the right. And with each time you open the door, stand over to the side so people can see what's inside and just hold the dollar amount up for the world to see. All right? The floor is yours. Find us the $50 bill.

20 No, that's good. That's good acting too. Thank you. No, you can shut it just like the computer, all right. No, very clear, thank you. Mm, still no $10 bill. Next locker. $5 bill, not going well. $100 bill, but not the one we want. This 1 $1 bill, still no $50. Of course, you've been sort of set up to fail, but here, amazing, a round of applause, Jose found the $50 bill.

All right, so let me ask you, Jose, you found the $50 bill. Um, it clearly took you a long time. Just describe in your own words what was your algorithm, even though I nudged you. Yeah, so my algorithm was basically walk up to the first door available, open it, check if the dollar bill was the dollar bill that I was looking for, and then put it back and then go. The next one. OK, so it's very reasonable because if the $50 bill were there, Jose was absolutely going to find it eventually, if slowly. In the meantime, Kelly's going to kindly reshuffle the numbers behind these doors here. And even though Jose took a long time here, I mean, what if Jose like wouldn't have been smart to start from the other end instead, do you think? Um, not necessarily because we don't know if the 50 is going to be at that end. Exactly. So he could have gotten lucky if he sort of flaunted my advice and didn't start on the left, but instead started on the right, boom,

he would have solved this in one step. But in general, that's not really going to work out. Maybe half the time it will, you'll get lucky, half the time it won't, but that. Not really a fundamental change in the algorithm whether you go left to right, right to left, to Jose's point, if you don't know anything a priori about the numbers, the best you can probably do is just go through linearly left to right or right to left, so long as you're consistent. Now, could you have jumped around randomly? Uh, I guess I could have, but if again, if they weren't in any like specified order, I don't think it would have helped either. Yeah, so and additionally, if he just jumped around to random order, then you might get lucky and it might be in the very first one, might have taken fewer steps ultimately, but presumably you're going to have to then keep track of like which locker doors have you opened. So that's going to take some memory or space. Not a big deal with 7 lockers, but if 70 lockers,

700 lockers, even random probably isn't going to be the best job. So let me go ahead and take the mic away and hand it over to Caitlin. You can stay on the stage with us. Caitlin, what I'd like you to do is approach this a little more intelligently by dividing and conquering the problem, but we're going to give you an advantage over Jose. Kelly has kindly sorted the numbers from smallest to largest from left to right. So accordingly, what's your strategy going to be? Start in the middle, OK, please. And go ahead as before and reveal to the audience what you found, not the 50, the 20, but what do you know, Caitlin, at this point? Correct.

So the 20 is going to be to the left. So where might you go next with this 3 locker problem? Let me propose that you maybe go to the middle of the 3. There we go, the middle of the middle. Like that would have been good, but let's. Oh no, oh no, it's up 100 instead. You failed, but what do you know? It's in the middle that I should have just let you, but. Now we have a big round of applause for Kaitlin for having found the 50 as well. OK. So the one catch with this particular demo is that because they know presumably what monopoly money denominations are, because we just did this exercise and we had the whole cheat sheet on the board, you probably had some intuition as to where the 50 was going to be, even though I was trying to get you to play along. But in the general case, if you don't know what the numbers are and that they are the specific denominations, but you do know that they're going from smallest to largest,

going to the middle, then the middle of the. Middle, then the middle of the middle again and again would have the effect of starting with a big problem and having it, having it, having it just like the phone book as well. So thanks to you both, we have these wonderful parting gifts that we found in Harvard Square. If you like Monopoly, you'll love the Cambridge edition filled with Harvard Square name spots. So thank you to you both, and a round of applause for our volunteers here. All right, so let's see if we can't formalize a little bit these two algorithms known as linear search insofar as Jose was searching essentially along a line left to right, and binary search by implying 2 because we were having that problem in 2 again and again and again. So for instance. Linar search from left to right or equivalently right to left, we could document our pseudo code as follows. For each door from left to right, if the 50 is behind the door, well then we're done.

Just return true. That's the boolean value which was the goal of this exercise to say yes, here is the 50. Otherwise, at the very bottom of this pseudo code, we could just say return false because if you get all the way through the lockers and you have never once declared true by finding the 50, you might as well default at the very end to saying false, I did not find it. But notice here, just like in week zero when we talked about pseudo code for. Searching the phone book, my indentation of all things is actually very intentional. This version of this code would be wrong if I instead used our old friend if else and made this conditional decision. Why is this code now in red wrong in terms of correctness? Yeah.

Exactly, because if the number 50 is not behind the first door, the E is telling you right then and there return false. But as we've seen in C code, whenever you return a value like that's it for the function, it is done doing its work. And so if you return false right away, not having looked at the other six lockers, you may very well get the answer wrong. So the first version of the code where there wasn't an L but rather this implicit line of code at the or this explicit line of code at the very end that just says if you. Reach this line of code returned false, that addresses that problem. And to be clear, even though it's right after an indented return true when you return a value as in C, that's it like execution stops at that point, at least for the function or in this case the pseudo code in question. All right, so here's a more computer sciencey way of describing the same algorithm

and even though it starts to look a little more arcane, the reality is when you start using variables and sort of standard notation you can actually. Express yourself much more clearly and precisely, even though it might take a little bit of practice to get used to. Here is how a computer scientist would express that exact same ideas instead of saying for each door from left to right we might throw some numbers on the table. So for I, a variable apparently from the value zero on up through the value and minus 1 is what this shorthand notation means. If 50 is behind doors bracket I, so to speak, so now. Sort of treating the notion of doors as an array using our notation from last week. If 50 is behind doors bracket I return true. Otherwise, if you get through the entirety of that array of doors, you can still return false. Now notice here N minus 1 seems a little weird because aren't there end doors? Why do I want to go from 0 to N minus 1 instead of 0 to end? Yeah.

Because um 0 is the first. Exactly, if you start counting at 0 and you have n elements, the last one is going to be addressed as n minus 1, not N, because if it were N, then you actually have N + 1 elements, which is not what we're talking about. So again, just a standard notation and it's a little terser this way. It's a little more succinct and frankly it's a little more adaptable to code. And so what you're going to find is that as our problem sets and programming challenges. We assign sort of get a little more involved. It's often helpful to write out pseudo code like this using an amalgam of English, and C, and eventually Python code, because then it's way easier after to just translate your pseudo code into actual code if you're operating at this level of detail. All right, so in the second algorithm where Caitlin kindly searched for 50 again, but Kelly gave her the advantage of sorting the numbers. Advance now she doesn't have to just resort to brute force,

so to speak, trying all possible doors from left to right. She can be a little more intelligent about it and pick and choose the locker she opens. And so with binary search as we call that, we could implement the same pseudo code or we could implement pseudo code for it as follows. We might say if 50 is behind the middle door, then go ahead and return true. Else if it's not behind the middle door, but 50 is less than that number behind the middle door, we want to go and search the left half so that didn't happen in Caitlin's sense because we ended up going right, so that's just another branch here. LA 50 is greater than what was at the middle door. We want to search the right half, but there's going to be one other condition here that we should probably consider, which is what?

Is it here, is it to the left, or is it to the right? But there's another a corner case that we'd better. Keep track of what else could happen if it's not in the ray or really like we're out of doors so we can implement this in a different way. I left myself some space at the top because I shouldn't do any of this if there are no doors to search for, so I should have this sort of sanity check whereby if there's no doors left or no doors to begin with, let's just immediately return false. And why is that? Well, notice that when I say search left half and search right half, this is implicitly telling me just do. This again, just do this again, but with fewer and fewer doors, and this is a technique for solving problems and implementing algorithms that we're going to end today's discussion on because what seems very colloquial and very straightforward, OK, search the left half, search the right half, is actually a very powerful programming technique that's going to enable us to write more elegant code, sometimes less code, to solve problems such as this and more on that in just a little bit.

But how can we Now formalize this using some of our array notation. Well, it looks a little more complicated, but it isn't really. Instead of asking questions in English alone, I might say if 50 is behind doors bracket middle. This soda code presupposes that I did some math and figured out what the numeric address, the numeric index is of the middle element and how can I do that? Well, if I've got 7 doors and I divide by 2, what's that? 7 divide by 2. 3.5, 3.5 makes no sense if I'm using integers to address this, so maybe we just round down, so 3, so that would be locker number 0123, which indeed if you look at the seven lockers is in fact the middle. So this is to say using some relatively simple arithmetic, I can figure out what the address is, the index is of the middle door. How many there are and I divide by 2 and round down. Meanwhile, if I don't find 50 behind the middle door, let's ask the question.

If 50 is less than the value at the middle door, then let's search, not the left half per se in the general sense, more specifically search doors 0 through doors bracket middle minus 1. Otherwise, if 50 is greater than the value at the middle door, go ahead and search doors bracket middle plus 1 through doors bracket and minus 1. Now let's consider these in turn. So searching the left half, as we described this earlier, seems to line up with this idea like start start searching from doors 0, the very first one, but why are we searching doors bracket middle minus 1 instead of doors bracket middle?

Yeah. Yeah, exactly. We already checked the middle door by asking this previous question, so you're just wasting everyone's time if you divide the half and still consider that door as checkable again. And same thing here. We check middle + 1 through the end of the locker's array because we already checked the middle one. So same reason, even though it just kind of complicates the look of the math, but it's really just using variables and arithmetic to describe the locations of these same lockers. But let's consider. Now what we mean by running time, the amount of time it takes for an algorithm to run, and consider which and why one of these algorithms is better than the other. So in general, when talking about running time, we can actually use pictures like this. This is not going to be some like very low level mathematical analysis where we count up lots of values. It's going to be broad strokes so that we can communicate to colleagues, to other humans, generally,

whether an algorithm is better than another and how you might compare the two. So here for instance is a pictorial analysis of two different algorithms the phone book from week zero and then the attendance taking from today itself. And let's generally, as we've done before, sort of label these things. So the very first algorithm took end steps in the very worst case if I had to search the whole phone book or if I had to count everyone in the room. So the first algorithm took indeed end steps. The second algorithm took half as many plus 1 maybe, but we'll keep it simple. So we'll call that N over 2. The third and final algorithm both in week 0 with the phone book and today with attendance is technically logbase 2 of N. And if you're a little rusty in your logarithms, that's fine. Just take on faith that logba 2 alludes to taking a problem of size N and dividing it in half and half and half as many times as you can

until you're left with one person standing or one page in the phone book. That's how many times you can divide in half a problem of size N. Well, it turns out that we're a little more detailed than most computer scientists care to get when describing the efficiency of algorithms. So in fact we're going to start to use some notation. Instead of worrying precisely mathematically about how many steps today's and the future's algorithms take, we're going to talk in broader strokes about how many steps there are on the order of, and we're going to use what's called big O notation, which literally is like a big O and then some parentheses, and you pronounce it big. of such and such. So the first algorithm seems to be in big O of n, which means it's on the order of N steps, give or take some. This algorithm here, you might be inclined to do something similar. It's on the order of N divided by 2 steps,

and this one's on the order of log based 2 of N steps, but it turns out what we really care about with algorithms is how the time grows as the problem it. Self grows in size. So the bigger end gets, the more concerned we are over how efficient our algorithm is. If only because today's computers are so darn fast, whether you're crunching 1000 numbers or 2000 numbers, like it's going to take like a split second no matter what. But if you're crunching 1000 numbers versus a million numbers versus a billion numbers, like that's where things start to actually be noticeable by us humans and we really start to care about these values. So in general, when using big O. like this, you ignore lower order terms or equivalently you only worry about the dominant term in whatever mathematical expression is in question. So big event remains big event. big O of N over 2, it's the same thing really as like big O over n. Like it's not really, but they're both linear in nature.

One grows at this rate, one grows at this rate instead, but it's for all intents and purposes the same. They're both growing at a constant rate. This one too uh it's on the order of log of n where the base is who cares? In short, what does this really mean? Well, imagine in your mind's eye that we were about to zoom out on this graph such that instead of going from 0 to like a million, maybe now the x axis is 0 to a billion, and same thing for the y axis 0 to a million. Let's zoom out so you're seeing. 0 to a billion. Well, in your mind's eye, you might imagine that as you zoom out, essentially things just get more and more compressed visually because you're zooming out and out and out, but these things still look like straight lines. This thing still looks like curved lines, which is to say as n gets large, clearly this green algorithm, whatever it is, is more appealing, it would seem than either of these two.

Algorithms and if we keep zooming out like at some point the ink is going to be so close together that they all are for all intents and purposes pretty much the same algorithm. So this is to say computer scientists don't care about lower order terms like divide by 2 or base 2 or anything like that. We look at the most dominant term that really matters is N gets bigger and bigger. So that then is big O notation. And it's something we'll start to use pretty much recurringly any time we analyze or speak to how good or how bad some algorithm is. So here's a little cheat sheet of common running times. So for instance, here's our friend big O of N, which means the algorithm takes on the order of end steps. Here is one that takes on the order of log N steps. Here are some others we haven't seen yet. Some algorithms take n times logn steps. Some algorithms take squared steps, and some algorithms just take one step, maybe, or maybe 2 steps or 4 steps or 10,

but a constant number of steps. So let me ask, if the algorithms we've looked at thus far, for instance, linear search being the very first today, what is the running time of linear search in big O notation? That is to say, if there's people, or if there's N lockers on the stage, how many steps might it take us to find a number among those N lockers? They go of, yeah. Big O of N in fact is exactly where I would put linear search. Why? Well, if you're using linear search in the very worst case, for instance, the number you're looking for, as with Jose, might be all the way at the end. So you might get lucky. It might not be at the very end, but generally it's useful to use this big O notation in the context of worst case scenarios because that really gives you a sense of how badly this algorithm could perform if you just get really unlucky with your data set.

So even though BigO really just refers to an upper bound, like how many steps might it take, it's generally useful to think about it in the context of like the worst case scenario, like, ah, the number I care about is actually way over here. But what about binary search? Even in the worst case, so long as the data is sorted, how many steps might binary search take by contrast? Big O of log in. So binary search we're going to put here, which is to say that in general, and especially as N gets large, binary search is much faster. It takes much less time. Why? Because assuming the numbers are sorted, you will be dividing in half and half and half, just like with the phone book in week 0, that problem, and you will get to your solution much faster. Why should you not use binary search though on an unsorted array of lockers?

Like a random set of numbers, yeah. Exactly, you're making these decisions based on inequalities less than or greater than, but based on like no rhyme or reason. You're going left going right, but there's no reason to believe that smaller numbers are this way and bigger numbers are that way. So you're just making incorrect decision after incorrect decision, so you're probably going to miss the number altogether. So binary search on an unsorted array is just incorrect, incorrect usage of the algorithm. But like Kelly did, if you sort the data in advance or you're handed sorted data, well then you can in fact apply binary search perfectly and much more efficiently.

Sure there is more efficient. Absolutely. Is Linear search sometimes more efficient if it's going to take you more time to sort the data and then use binary search? Absolutely. And that's going to be one of the design decisions that underlies any implementation of an algorithm because if it's going to take you some crazy long time, not to sort like 7 numbers, but 70, 700, 7000, 7 million, but you only need to search the data once, then what the heck are you doing? Like why are you wasting time sorting. Data, if you only care about getting an answer once, you might as well just use linear search or heck, do it even randomly and hope you get lucky if you don't care about reproducing the same result. Now, in general, that's not how much of the world works. For instance, Google's working really hard to make faster and faster algorithms because we are not searching Google once and then never again doing it. We're doing it again and again and again so they can amortize. So to speak,

the cost of sorting data over lots and lots of searches, but sometimes it's going to be the opposite. And I think back to graduate school, where I was often writing code to analyze large sets of data, and I could have done it the right way, sort of the CS 50 way, by fine tuning my algorithm and thinking really hard about my code, but honestly, sometimes it was easier to just write really bad but correct code, go to sleep for 7 hours, and then my computer would have the answer by morning. The downside, as admittedly happened more than once, is if you have a bug in your code and you go to sleep and then 7 hours later you find out that there was a bug, you've just wasted the entire evening, so there too a trade off sometimes when making those resource decisions. But that's entirely what today is about making informed decisions and sometimes maybe it's smarter and wiser to make the more expensive decision, but not unknowingly, at least knowingly. All right,

so there we have our first two algorithms, but let's consider another way of describing the efficiency of an algorithm. Big O is an upper bound, sort of how bad can it get in these cases where maybe the data is really not working to our advantage. Omega, a capital Omega symbol here is used for lower bounds. So maybe how lucky might we get in the best case, if you will, how few steps might an algorithm take? Well, in this case here, here's just a cheat sheet of common run times, even though there's an infinite number of others, but we'll generally focus on functions like these. Let's consider those same algorithms. So with linear search from left to right, how few steps might that algorithm take?

For instance, in like the best case scenario. Yeah, is this uh hand about to go up? Yeah, so one step why because maybe Jose could have gotten lucky and opened the door and voila, that was the 50. It didn't play out that way, but it could have. In the general case, the number you're looking for could very well be at the beginning. So we're going to put linear search at omega of 1. So one step, and maybe it's technically a few more than that, but it's a fixed number of steps that Nothing to do with the number of lockers. Case in point, if I gave you not 7, but 70 lockers, you could still get lucky and still take just one step. So Omega is our lower bound, Big O is our upper bound. Ah, spoiler, what is binary search is lower bound. Well, apparently it's also omega of 1, but why? That is in fact correct, yeah.

Same reason you could get lucky in the best case, and it's just smack dab in the middle of all of the data. So the fewest number of steps binary search might take is also actually one. So this is why we talk about upper bound and lower bound because you get kind of a, a sense of the range of performance. Sometimes it's going to be super fast, which is great, but something tells me in the general case we're not going to get lucky every time we use an algorithm, so it's probably going to be closer to those upper bounds, the big. Now, as an aside, there's a 3rd and final symbol that we use in computer science to describe algorithms, that of a capital theta. Capital theta is jargon you can use when big O and Omega happen to be the same, and we'll see that today, not always, but here's a similar cheat sheet. None of the algorithms thus far can be described in this way with theta notation because they are not all the same. With their big O and Omega,

they differed in both of our analyses, but we'll see at least one example of one where it's like, OK, we can describe this in theta, and that's like saying twice as much information with your words to another computer scientist rather than giving them both the upper and the lower bounds. The fancy way of describing all of what we're talking about here, big O, omega, and theta is asymptotic notation, and asymptotic notation refer or. Asymptoticle refers to a value getting bigger and bigger and bigger and bigger but not necessarily ever hitting some boundary as N gets very large. In short, is what we mean when we deploy this here asymptotic notation. All right, so with the first of these things like linear search, let's actually kind of make this a bit more real. Let me actually go over to in just a moment. Uh my other screen here, OK, in VS code, let me go ahead and create a program called Search.c. and in search.c,

let's go ahead and implement a fairly simple version of Linar search initially. So let me go ahead and include, for instance, CS50.h. Let me go ahead and include standardio.h. Then let me go ahead and do main void, so we're not going to bother with any command line arguments for now. And then let me go ahead and just give myself an array of numbers to play with. And we did this briefly last week in answer to a question, but I'm going to do it now concretely rather than use something more manual to get all of these numbers into the array. I'm going to say give me an array called numbers, and the numbers I want to put in this array initially are going to be the exact same denominations we've been playing with 20, 500, 10, 5, 100, 1, and 50. Again, this is a notation that I alluded to in answer to a question last week whereby if you want. To statically initialize an array that is give it all of your values up front without having the human type them all in manually.

You can use curly braces like this, and the compiler is pretty smart. You don't have to bother telling the compiler how many numbers you want 1234567 because it can obviously just count how many numbers are in the curly braces, but you could explicitly say 7 there so long as you're counting is in fact correct. So on line 6 this gives me an array of 7 numbers. Initialize to precisely that list of numbers from left to right. All right, let's ask the human now what number they want to search for, just as I did our two volunteers and say in N equals get in, then let's just ask the user for the number that they want to search for. Then let's implement linear search. And if I want to implement linear search in terms of the programming constructs we've seen thus far, like what type, what keyword in C should I use? What programming technique, yeah. Yeah, so maybe a 4 loop or a Y loop, but 4 loop is kind of my go to lately.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent