- Hackr.io Newsletter
- Posts
- How Do You Build a Merge Sort Algorithm?
How Do You Build a Merge Sort Algorithm?
With Neuralink news and code for the full Python project.
This week, we’re diving into a popular Python project, addressing a programming question, highlighting a few news stories, and sharing new job opportunities.
News and Resources
In-Depth on the Merge Sort Algorithm
This divide-and-conquer strategy uses division to separate a list of numbers into equal parts, and these are then recursively sorted before being recombined to generate a sorted list.
In essence, this Python program continues to recursively divide the list until it reaches the base case.
At this point it begins sorting the smaller parts of the problem, resulting in smaller sorted arrays that are recombined to eventually generate a fully sorted array. If you’re familiar with Big O notation, you’ll be curious to know that Merge Sort has a Big O of (n logn).
So how do you build this Python project? Here’s the code.
'''
Merge Sort
-------------------------------------------------------------
'''
def merge_sort(a_list):
print("Dividing ", a_list)
if len(a_list) > 1:
mid_point = len(a_list)//2
left_half = a_list[:mid_point]
right_half = a_list[mid_point:]
merge_sort(left_half)
merge_sort(right_half)
i=0
j=0
k=0
while i < len(left_half) and j < len(right_half):
if left_half[i] <= right_half[j]:
a_list[k] = left_half[i]
i += 1
else:
a_list[k] = right_half[j]
j += 1
k += 1
while i < len(left_half):
a_list[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
a_list[k] = right_half[j]
j += 1
k += 1
print("Merging ", a_list)
if __name__ == '__main__':
a_list = [45, 7, 85, 24, 60, 25, 38, 63, 1]
merge_sort(a_list)
print(a_list)
View all the most popular Python projects at Hackr.
This Week’s Job Opportunities
Senior Development Engineer, Miami, FL - Hybrid
Data Center Engineer, Dallas, TX
Senior Developer Technology Engineer - AI, Santa Clara, CA
Sr. Full Stack Engineer, Fully Remote
Data Modeler, Waukegan, IL
If you’re finding this helpful, please share our newsletter with a friend. Thanks for being part of our community!
Learn Python from a Pro
To ace an interview, you need to understand Python without relying on autocorrect. Dr. Johns teaches the WHY behind the code. This masterclass also includes the full module on how to build a chatbot with Python.
Use the code MAY in your cart to get 40% off the course. Here’s where you can get more information.
Rate this NewsletterThe team at Hackr.io aims to provide the best information possible. Please let us know how we're doing! |