Quick Sort Function
Anonymous
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
python1def quick_sort(arr): 2 if len(arr) <= 1: 3 return arr 4 pivot = arr[len(arr) // 2] 5 left = [x for x in arr if x < pivot] 6 middle = [x for x in arr if x == pivot] 7 right = [x for x in arr if x > pivot] 8 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:
python1import unittest 2 3class TestQuickSort(unittest.TestCase): 4 def test_quick_sort(self): 5 self.assertEqual(quick_sort([3, 6, 8, 10, 1, 2, 1]), [1, 1, 2, 3, 6, 8, 10]) 6 self.assertEqual(quick_sort([]), []) 7 self.assertEqual(quick_sort([1]), [1]) 8 self.assertEqual(quick_sort([1, 2, 3]), [1, 2, 3]) 9 self.assertEqual(quick_sort([3, 2, 1]), [1, 2, 3]) 10 11if __name__ == '__main__': 12 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.