사용자
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)
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)
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.
arr: A list of elements to be sorted. The elements in this list should be comparable with each other using comparison operators.arr, sorted in ascending order.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)
To test the quick_sort function, we can use Python's unittest framework. Below is a sample unit test:
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.