import unittest
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
left = [x for x in arr[1:] if x < pivot]
right = [x for x in arr[1:] if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
class TestQuickSort(unittest.TestCase):
def test_empty_array(self):
self.assertEqual(quick_sort([]), [])
def test_single_element_array(self):
self.assertEqual(quick_sort([5]), [5])
def test_sorted_array(self):
self.assertEqual(quick_sort([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5])
def test_reverse_sorted_array(self):
self.assertEqual(quick_sort([5, 4, 3, 2, 1]), [1, 2, 3, 4, 5])
def test_unsorted_array(self):
self.assertEqual(quick_sort([3, 7, 8, 5, 2, 1, 9, 4, 6]), [1, 2, 3, 4, 5, 6, 7, 8, 9])
def test_array_with_duplicates(self):
self.assertEqual(quick_sort([3, 7, 8, 5, 2, 1, 9, 4, 6, 3, 7]), [1, 2, 3, 3, 4, 5, 6, 7, 7, 8, 9])
if __name__ == '__main__':
unittest.main()
Spiegazione dei test:
test_empty_array
: controlla se la funzione gestisce correttamente un array vuoto.
test_single_element_array
: controlla se la funzione gestisce correttamente un array con un singolo elemento.
test_sorted_array
: controlla se la funzione ordina correttamente un array già ordinato.
test_reverse_sorted_array
: controlla se la funzione ordina correttamente un array con ordine inverso.
test_unsorted_array
: controlla se la funzione ordina correttamente un array non ordinato.
test_array_with_duplicates
: controlla se la funzione gestisce correttamente un array con elementi duplicati.
Esecuzione dei test:
Per eseguire i test, salva il codice come file Python (ad es. test_quick_sort.py
) ed eseguilo dalla riga di comando:
python test_quick_sort.py
In questo modo i test verranno eseguiti e i risultati verranno stampati. Se tutti i test hanno esito positivo, dovresti vedere un output simile al seguente:
....
----------------------------------------------------------------------
Ran 6 tests in 0.001s
OK