Pseudo Code
Lesson 4 of 9 in Coddy's Merge Sort - DSA Series course.
mergeSort(array):
if length(array) <= 1:
return array
mid = length(array) / 2
left = mergeSort(array[0..mid])
right = mergeSort(array[mid..end])
return merge(left, right)
merge(left, right):
result = []
while left and right both still have elements:
if left[0] <= right[0]:
move the front of left into result
else:
move the front of right into result
append whatever remains of left
append whatever remains of right
return resultTwo functions work together:
- mergeSort keeps splitting the array until the pieces are trivially sorted, then relies on merge to combine them.
- merge walks two sorted lists at once, always taking the smaller front element, so the combined list stays sorted.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Merge Sort - DSA Series
2The Algorithm
How it works?Pseudo CodeImplementation (Part 1)Implementation (Part 2)