Simpler Insertion Sort Function
⇐ Use this menu to view and help create subtitles for this video in many different languages. You'll probably want to hide YouTube's captions if using these subtitles.
Simpler Insertion Sort Function : Simplifying the while loop for the Insertion Sort function
- It was pointed out in the comments for the last video where
- I defined this insertion sort that I didn't necessarily
- have to do this break, the logic, and this is one of those
- examples that sometimes when you just program something and
- the way that your brain is at least thinking about it
- you don't always do it in maybe the most elegant way
- and that commenter was right. There was a slightly more,
- or a lot more elegant way to do this insertion sort.
- So, over here if we go into the WHILE loop,
- I have this WHILE loop
- happening WHILE I is greater than or equal to zero
- But then, I want to essentially BREAK out of that WHILE loop
- if the variable value is not less than the I-th element in list
- So, one way to do this, cause I'm just defining the parameters
- on when to do this WHILE loop. Instead of this IF the value is
- less than the I-th element, do this, otherwise
- BREAK, what I could've of done, and is actually the more
- elegant way to do this, WHILE I is greater than or equal
- to zero AND value is less than than I-th element in list
- so now I know that value is less than the I-th element of the
- list, and I will execute this code over here, so I know that this
- is going to be true. I know that this is going to be true and I can
- I can auto take all of these one level back and then I don't have
- to do an ELSE and I don't have to BREAK out of the loop anymore
- so that should simplify the program a good bit. But, let's verify
- for ourselves that this actually works, so let me save it. And then
- let me run it, looks like its...let me define a list, so let me call
- it, I'll just call it C is equal to one, five, six, seven
- two, four, fourteen and two. So let's just define that and let's try
- our insertion sort. Insertion sort on C, let's see what we get.
- So let's see, let's print C now and there you go.
- It sorted it. So thank you for the comment.
- I think this does simplify it a little bit and
- it shows that sometimes you always have to question
- especially if you have a WHILE statement, is there a better
- way instead of using a BREAK because I'm putting a condition
- on a reason to BREAK out of the WHILE loop, why don't I
- implicitly just put it up here.