I want to share with you three algorithms to keep in mind when developing your next application. These algorithms will improve the functionality of your app and they are not complicated to implement. They are the:
- Binary Search Tree
- Heap Data Structure
- Stack Data Structure.
Binary Search Tree
So you get hired to implement a new social media platform. The client expects the popularity of the platform to grow to two million members within a month. What data structures would you use to store the names of all members?
Would you use an array? Or would you use a linked-list?
Novice developers would use an array. This is such a bad idea. Arrays are static. They don't grow dynamically. More experience developers would implement a linked-list. Linked-list grow dynamically. They are better suited for the future growth of the social platform.
However, both of these structures are terrible if you want to search a list of 2 million members. This is because these structures are only capable of doing linear searches.
Arrays or linked-lists are OK if you have 10-100 elements, but they are terrible if your list have 10,000 elements or more.
Experienced developers know this. And they would implement a Binary Search Tree instead. Doing a search with 2 million members would take a fraction of the time a linear search would.
Heap Data Structure
Or let's say that the client is expecting to sort her list of two million members by age. Novice developers will do this by brute force. Comparing the age of each member in the array and swapping them.
Trust me, if you have two million members to sort, it will take you a whole day and will bring down the system. An experienced developer will take the array structure and convert it into a Heap structure.
He will then Heapify the Heap Structure and perform a Heap Sort Algorithm. Doing a Heap Sort algorithm is order of magnitudes more efficient than swapping by brute force.
Stack Data Structure
Or let's say that you are developing an application with an "Undo" feature. Where would you store all the user's recent operations? In an array? Sure, that is fine, but this would mean that the user could only perform a limited number of Undos.
What if the user needs an unlimited number of Undos? (Assuming you have all the memory in the world)
The best data structure to accomplish this is a Stack structure. A Stack allocates memory dynamically. It functions as a Last-in, First-out algorithm. With this type of data structure, an Undo feature can be done beautifully.
Keep these algorithms in mind the next time you need to search a list, sort a list or create an undo feature.