gpt-4-turbo-2024-04-09· OpenAI
WildChat-4.8M (AI2)
write a quick sort code python
- User
write a quick sort code python
- Assistant
Quick sort is a popular sorting algorithm that utilizes the divide and conquer strategy. Below you'll find a simple implementation of QuickSort in Python:
pythondef quick_sort(arr): """ Quick sort function that sorts a list. Args: arr (list): The list to be sorted. Returns: list: The sorted list. """ if len(arr) <= 1: return arr else: pivot = arr[len(arr) // 2] # Choose the middle element as the pivot 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 quick_sort(left) + middle + quick_sort(right) # Example usage example_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] sorted_list = quick_sort(example_list) print(sorted_list)