Junior — Middle
Explain the merge sort algorithm and its main stages.
sobes.tech AI
Answer from AI
Merge sort algorithm is an efficient sorting algorithm based on the "divide and conquer" principle. It works as follows:
- Divide: The original array is recursively divided into two halves until each part becomes of size 1 (or empty).
- Sort: Each of these small parts is considered sorted by definition.
- Merge: The sorted parts are sequentially merged into larger sorted arrays until the entire original array is sorted.
The main idea is to break down the problem into simpler subproblems, sort them, and combine the results.
Example in Python:
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
# Usage example
arr = [38, 27, 43, 3, 9, 82, 10]
sorted_arr = merge_sort(arr)
print(sorted_arr) # [3, 9, 10, 27, 38, 43, 82]