Algorithm Examples You Should Know in Python

if left.

length == 0 merged_arr << right.

shift elsif right.

length == 0 merged_arr << left.

shift elsif left <= right merged_arr << left.

shift elsif right <= left merged_arr << right.

shift end end merged_arrendMerge Sort has a time complexity of O(nlog n), which is the best possible time complexity for a sorting algorithm.

By dividing and conquering, we dramatically improve the efficiency of sorting, which is already a computationally expensive process.

3.

Adding and Removing From a Linked ListThe linked list is a fundamental computer science data structure, that is most useful for it’s constant time insertion and deletion.

By using nodes and pointers, we can perform some processes much more efficiently than if we were to use an array.

See below for a schematic:A linked list is made up of nodes which each have a piece of data and a pointer to the next node.

We represent this in Ruby by creating a struct, Node, with two arguments, :data and :next_node.

Now, we just have to define two methods, insert_node and delete_node that take in a head node and a location of where to insert/delete.

The insert_node method has an additional argument, node, which is the node struct we want to insert.

We then loop until we find the location we would like to insert into or delete from.

When we arrive at our desired location, and rearrange the pointers to reflect our insertion/deletion.

Node = Struct.

new(:data, :next_node)def insert_node(head, node, location) current_node = head current_location = 0 until current_location == location previous_node = current_node current_node = current_node.

next_node current_location += 1 end if previous_node previous_node.

next_node = node node.

next_node = current_node else node.

next_node = current_node end headenddef delete_node(head, location) current_node = head current_location = 0 until current_location == location previous_node = current_node current_node = current_node.

next_node current_location += 1 end if previous_node previous_node.

next_node = current_node.

next_node else head = current_node.

next_node end headendWith a linked list, we can delete items from the middle of a collection without having to shift over the rest of the data structure in memory, like we would have to if we were using an array.

By choosing the best data structure for our needs, we can reach optimal efficiency!What’s Next?These three algorithm examples are just the surface of fundamental algorithms we should know to both create efficient programs and succeed at technical interviews.

Here are some more algorithms we can explore on our own to further our knowledge.

QuicksortTraverse a binary search treeMinimum spanning treeHeapsortReverse a string in placeThese are difficult concepts to grasp, so we just have to keep practicing and understand more algorithm examples!.