Write a python code to implement quick sort
- User
Write a python code to implement quick sort
- Assistant
Sure, here's an example implementation of quick sort in Python:
def quick_sort(arr): if len(arr) <= 1: return arr else: pivot = arr[0] left = [] right = [] for i in range(1, len(arr)): if arr[i] < pivot: left.append(arr[i]) else: right.append(arr[i]) return quick_sort(left) + [pivot] + quick_sort(right)This implementation uses the first element of the array as the pivot, and then partitions the array into two sub-arrays based on whether their elements are less than or greater than the pivot. It then recursively applies the same process to each sub-array and concatenates the results.
To use this implementation, you can simply call the quick_sort() function and pass in the array you want to sort as an argument, like this:
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_arr = quick_sort(arr) print(sorted_arr) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]I hope this helps!
- User
Thanks! Can you now add comments to the function so it's easier to understand? Also please add tests to ensure that the function is working correctly.
- Assistant
Sure, here's the updated code with comments and tests:
def quick_sort(arr): """ This function implements the quick sort algorithm to sort an input array in ascending order.
Parameters: arr (list): The input list to be sorted Returns: list: The sorted list """ # Base case: If the input list is empty or contains only one element, return it as is if len(arr) <= 1: return arr else: # Choose the first element of the list as the pivot pivot = arr[0] # Partition the input list into two sub-lists based on the pivot left = [] right = [] for i in range(1, len(arr)): if arr[i] < pivot: left.append(arr[i]) else: right.append(arr[i]) # Recursively apply quick sort to the two sub-lists and concatenate the results return quick_sort(left) + [pivot] + quick_sort(right)Tests
arr1 = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_arr1 = quick_sort(arr1) print(sorted_arr1) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →