Python Development Assistant

Quick Sort Function

Python Development Assistant

Öffnen Sie den ursprünglichen geteilten Chat

Benutzer

def quick_sort(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 quick_sort(left) + middle + quick_sort(right)

Python Development Assistant

### Function Annotation #### Function Description `quick_sort(arr)` - This function implements the Quick Sort algorithm. It takes a list of elements and returns a new list with the elements sorted in ascending order. #### Parameters - `arr`: A list of elements to be sorted. The elements in this list should be comparable with each other using comparison operators. #### Return Value - The function returns a new list containing the elements from the input list `arr`, sorted in ascending order. ### Function Code ```python def quick_sort(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 quick_sort(left) + middle + quick_sort(right) ``` ### Unit Test Code To test the `quick_sort` function, we can use Python's unittest framework. Below is a sample unit test: ```python import unittest class TestQuickSort(unittest.TestCase): def test_quick_sort(self): self.assertEqual(quick_sort([3, 6, 8, 10, 1, 2, 1]), [1, 1, 2, 3, 6, 8, 10]) self.assertEqual(quick_sort([]), []) self.assertEqual(quick_sort([1]), [1]) self.assertEqual(quick_sort([1, 2, 3]), [1, 2, 3]) self.assertEqual(quick_sort([3, 2, 1]), [1, 2, 3]) if __name__ == '__main__': unittest.main() ``` To run these tests, simply copy the test code into a Python script where the `quick_sort` function is defined and execute the script.