Lecture
Implementing Merge Sort
1. Divide: Split the original list into two parts as evenly as possible.
Division Example
mid = len(arr) // 2 L = arr[:mid] R = arr[mid:]
2. Recursive Sorting: Recursively sort each part.
Recursive Sorting Example
merge_sort(L) merge_sort(R)
3. Merge: Combine the two sorted parts into one sorted list.
Merge Example
i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1
Time Complexity
-
Worst-case time complexity: O(nlog n)- Merge sort maintains a consistent time complexity during the divide and merge processes. At each level, the array is split in half, and for each level, it performs (n) operations. Therefore, it performs a total of (n) operations over ( \log n ) levels.
-
Best-case time complexity: O(nlog n)- Even in the best case, merge sort proceeds with the same division and merge process, so the time complexity remains unchanged.
-
Average time complexity: O(nlog n)- In general cases, merge sort maintains a consistent time complexity of (O(n log n)). It requires the same amount of work regardless of the initial sorted state of the array.
Lessons in this chapter · Practical Python Algorithms
- 1. Advanced Python Algorithms
- 2. What is a Recursive Call?
- 3. Implementing Fibonacci Sequence with Recursive Function
- 4. Fill-in-the-blank quiz
- 5. Coding Quiz - Fibonacci Sequence
- 6. Dynamic Programming and Divide and Conquer
- 7. Implementing Dynamic Programming in Python
- 8. Multiple-choice quiz
- 9. Coding Quiz - Make One
- 10. What is Merge Sort?
- 11. Implementing Merge Sort
- 12. Multiple-choice quiz
- 13. Coding Quiz - Sort a List Using Merge Sort
- 14. What is Quick Sort?
- 15. Implementing Quick Sort in Python
- 16. Multiple-choice quiz
- 17. Coding Quiz - Sort a List Using Quick Sort
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help