Binary Search Algorithm - Python Example & Code

Tech With Tim · Intermediate ·⚡ Algorithms & Data Structures ·8y ago

Key Takeaways

Implements the Binary Search Algorithm in Python

Full Transcript

[Music] welcome back to another YouTube video so in today's video I'm going to be talking about the binary search algorithm now in the last video we talked about the linear search algorithm a very simple algorithm pretty much if this was our list it looks around the beginning to the end of the list until it found the element that we were looking for this search algorithm is much faster especially on large data sets and it has log n Big O notation meaning that it gets exponentially faster as the data set gets larger so this is extremely useful and it's a lot more useful than the linear search has more applications so let's get right into how it works so this is gonna be a list up here just for example purposes I know it's extremely simple but it's just easy to illustrate how things work with a small list now binary meaning 2 means that we're gonna have two main comparisons in this in this search it's gonna be greater than and less than so what we're gonna do is we're gonna find the middle indicee this what the algorithm does finds the middle indicee or index of the list which in this case would be 5 now it's gonna compare the element where that we're looking for and right now we're gonna be looking for one to this element it's gonna say is 1 greater than 5 no it's not is 1 lesson 5 yes it is now once we know this information we then split up the list or the algorithm splits up the list so if we know that 1 is less than 5 why would we continue to look this way if we know it's gonna be in the bottom half of the list so now we have a list of 1 2 3 4 and the same process repeats itself so now we have this list and we're gonna look at the middle indices now notice this is not an odd numbered list so because of this the industry we're going to be checking is here it doesn't really matter which one you check if you check this one or this one we're just gonna be checking this one and then we're gonna say well is 1 less than 2 yes it is so now we create a list that only has 1 in it and then we find that since there's only one element in it and that's the element we're checking that is 1 all right so I know I went kind of fast a little bit confusing but as I go through the code of this algorithm you'll understand hopefully how this works so this is my function here it's not too complex and it is fairly simple to code so we're gonna start off by sorting our list so I mentioned that this algorithm only works if the list is sorted and obviously that's because if we have these in different orders we wouldn't be able to do the same comparisons that we're doing in the algorithm now we start by setting two variables a top and a bottom variable so our top is gonna be the top section of the list and the bottom is gonna be the bottom of a section list and rather than recreating a bunch of different lists every time we we split it up or we do a comparison we're just gonna be looking at a different part of the list so rather than recreating a list which gonna take more time and more memory we're just looking at a different section of the original list that makes sense so we have our top our bottom this is gonna be the whole list because we start at 0 and we go to the last in the scene and then here I just print this out just so we can see we'll be able to see when we run the program and now we find our middle indicee in this while loop so this middle indicee is gonna be the top plus the bottom / - just how you find example midpoint of a line or the middle of a list and this integer division is very important because if we get something like we have 5 for example and we divide by 2 then we're gonna be getting in decimal number which we don't want all right and then we do our comparisons so we start by checking well is the element that we're looking for right here equal to the element in the list that we're comparing it to so pretty much the 1 step here so once we check the middle indicee we're gonna first see well if the element that we're looking for is equal to that middle indicee we've now found it we don't need to continue to look through the list if it's not equal to that then we move down and we say well is it less than the middle indices or whatever that element is if it is then we're gonna be setting our top to our middle and what that does is it moves pretty much at the top is here at 9 it moves it down to 5 so that we can then look through the next section of the list like that and then the next part here so we say if element is greater than and then same thing so we're gonna move our bottom to the middle so what we do is we have this is our bottom we would then move it up here so now the next section of our list is this and you can see how this continues to go on now it is to be noted here I could just put an else statement the reason I put Elif is just to illustrate more clearly exactly how this works because obviously if it's not equal to it's not less than it's gonna be greater than if it's a number and this does work for strings in Python so in Python you can actually I'll show you down here you could actually do for example something like this like that and that would actually work as a comparison it's really weird compared to other languages but it does work so you can compare strings like that so this will work for Strings if you're using Python and then down here this is just where I create a random list of integers and then I just select a random integer to look for it in the list so if we go ahead and run the program here save it then you can see I just simply am printing out the length of the list to show you how many comparisons were actually doing so we start with ten thousand five thousand 2500 1250 so on having each time now as we get down to the end here we have ten elements left and at this point we've now found the element we're looking for which is at the twelve hundred and fifteenth index now this is extremely efficient and you can see already that if I had tried to do ten thousand items in a linear search and say maybe we got unlucky and the item we were looking for was at the very end we would still be waiting for that search to go on so you can see how much faster this actually gets now if I just add another zero here tour at the length of our list a hundred thousand we can run it again and you see we're going it's extremely fast considering the amount of items in our list if I'm not if I don't print this it should pop up almost instantly oops comment that out and yeah you can see we get that almost instantly now again if we go to 1 million there we go we're getting hit again almost instantly 10 million let's see how fast this one goes and we're taking a little bit longer on this one which is to be expected so yeah you can see that the binary search is extremely efficient and it's obviously better to use a linear search if you're using longer or larger data sets the reason we would use linear search over this is only because of this aspect right here if you look if you're looking at a small data set and you don't want to sort it first then you just use a linear search so yeah this has been the video on the binary sorry not sort search algorithm I've just been saying sort for a long time now haven't I I hope you guys enjoyed if you did please leave a like and subscribe and I will see you again [Music]

Original Description

Binary Search Algorithm in Python. I give a tutorial and explanation of the binary search algorithm implemented in python. In this video I explain how the binary search algorithm works. I go through a detailed explanation of the efficiency, bigO notation and strengths and weaknesses for this algorithm. I do this all in python 3.6. I also give example code that you can use if you want to implement this into your own program. Please LIKE and SUBSCRIBE for more content! Tags: - Binary search python - Binary search algorithm - How does binary search work - Binary search tutorial - how to code binary search python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Tech With Tim · Tech With Tim · 39 of 60

1 A* Path Finding Algorithm(Visualization)
A* Path Finding Algorithm(Visualization)
Tech With Tim
2 Python Programming Tutorial #1 - Variables and Data Types
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
3 Python Programming Tutorial #2 - Basic Operators and Input
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
4 Python Programming Tutorial #3 - Conditions
Python Programming Tutorial #3 - Conditions
Tech With Tim
5 Python Programming Tutorial #4 - IF/ELIF/ELSE
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
6 Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
7 Python Programming Tutorial #6 - For Loops
Python Programming Tutorial #6 - For Loops
Tech With Tim
8 Python Programming Tutorial #7 - While Loops
Python Programming Tutorial #7 - While Loops
Tech With Tim
9 Python Programming Tutorial #8 - Lists and Tuples
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
10 Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
11 Python Programming Tutorial #10 - String Methods
Python Programming Tutorial #10 - String Methods
Tech With Tim
12 How to Overclock a NVIDIA GPU
How to Overclock a NVIDIA GPU
Tech With Tim
13 Python Programming Tutorial #11 - Slice Operator
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
14 Python Programming Tutorial #12 - Functions
Python Programming Tutorial #12 - Functions
Tech With Tim
15 Python Programming Tutorial #13 - How to Read a Text File
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
16 Python Programming Tutorial #14 - Writing to a Text File
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
17 Python Programming Tutorial #15 - Using .count() and .find()
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
18 Python Programming Tutorial #16 - Introduction to Modular Programming
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
19 Python Programming Tutorial #17 - Optional Parameters
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
20 Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
21 Python Programming Tutorial #19 - Global vs Local Variables
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
22 Python Programming Tutorial #20 - Classes and Objects
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
23 Cool VBS Script to Prank Your Friends!
Cool VBS Script to Prank Your Friends!
Tech With Tim
24 How to Overclock an AMD GPU
How to Overclock an AMD GPU
Tech With Tim
25 Best GPU'S For Mining Ethereum (2018)
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
26 Recursion and Memoization Tutorial Python
Recursion and Memoization Tutorial Python
Tech With Tim
27 Ethereum Mining Rig - Hardware Guide
Ethereum Mining Rig - Hardware Guide
Tech With Tim
28 Pygame Tutorial #1 - Basic Movement and Key Presses
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
29 How to Install Pygame (Windows 8/10)
How to Install Pygame (Windows 8/10)
Tech With Tim
30 How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
31 How to Mine Ethereum 2018 - WORKING (Super-Easy)
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
32 Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
33 Pygame Tutorial #2 - Jumping and Boundaries
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
34 Pygame Tutorial #3 - Character Animation & Sprites
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
35 Pygame Tutorial #4 - Optimization & OOP
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
36 OBS Studio Tutorial - Best OBS Settings
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
37 Linear Search Algorithm - Python Example and Code
Linear Search Algorithm - Python Example and Code
Tech With Tim
38 Make Any Mic Sound AMAZING! (WITH OBS)
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
Binary Search Algorithm - Python Example & Code
Binary Search Algorithm - Python Example & Code
Tech With Tim
40 Pygame Tutorial #5 - Projectiles
Pygame Tutorial #5 - Projectiles
Tech With Tim
41 Pygame Game - Mini Golf
Pygame Game - Mini Golf
Tech With Tim
42 Pygame Tutorial - Projectile Motion (Part 1)
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
43 Pygame Tutorial - Projectile Motion (Part 2)
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
44 Pygame Tutorial #6 - Enemies
Pygame Tutorial #6 - Enemies
Tech With Tim
45 Pygame Tutorial #7 - Collision and Hit Boxes
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
46 Pygame Tutorial #8 - Scoring and Health Bars
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
47 Cloud Mining vs. Hardware Mining - 2018
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
48 How to Install Pygame on Mac OSX (Fast-Simple)
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
49 Pygame Tutorial #9 - Sound Effects, Music & More Collision
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
50 Pygame Tutorial #10 - Finishing Touches & Next Steps
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
51 How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
52 How to Create a Button in Pygame [CODE IN DESCRIPTION]
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
53 Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
54 Pygame Side-Scroller Tutorial #2 - Random Object Generation
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
55 Pygame Side-Scroller Tutorial #3 - Collision
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
56 Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
57 How to Create A Message Box in Python - Tkinter
How to Create A Message Box in Python - Tkinter
Tech With Tim
58 Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
59 How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
60 Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim

Related Reads

Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →