Handling Duplicate Elements in a Custom QuickSort Implementation in Python - Stack Overflow scenarios
I'm trying to figure out I'm currently implementing a custom QuickSort algorithm in Python to sort an array that may contain duplicate elements. However, I'm running into a Stack Overflow behavior when the input has many repeated values, which I suspect is due to excessive recursion depth. I'm using Python 3.9, and here's my implementation: ```python def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right) ``` When I test it with an array like this: ```python input_array = [5, 5, 5, 5, 5, 5, 5, 5, 5, 5] print(quicksort(input_array)) ``` I get a `RecursionError: maximum recursion depth exceeded in comparison`. I considered switching to an iterative approach but Iām not sure how to effectively implement that with QuickSort. I also tried increasing the recursion limit with `sys.setrecursionlimit()`, but that just leads to a different kind of behavior due to memory issues. Is there a way to modify my QuickSort implementation to handle duplicates better without running into stack overflow issues? Should I use a different sorting algorithm in cases where the input array has many duplicate values? Any insights would be appreciated!