Ciao, vorrei un'implementazione del quicksort in pyton
- User
Ciao, vorrei un'implementazione del quicksort in pyton
- Assistant
Ciao! Ecco un'implementazione del QuickSort in Python:
def quicksort(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 quicksort(left) + middle + quicksort(right) arr = [3,6,8,10,1,2,1] print("Array prima del sorting:", arr) print("Array dopo il sorting:", quicksort(arr))Spiegazione dell'implementazione:
- La funzione
quicksortprende come input un array. - Se l'array ha lunghezza 0 oppure 1, viene restituito direttamente, poiché è già ordinato.
- Viene scelto un pivot, che in questo caso è l'elemento presente a metà dell'array.
- Viene creato un array
leftche contiene gli elementi minori del pivot, un arraymiddleche contiene gli elementi uguali al pivot, e un arrayrightche contiene gli elementi maggiori del pivot. - Infine, gli array
lefterightvengono ordinati ricorsivamente con la stessa funzione , e vengono concatenati insieme a per restituire l'array ordinato.
- La funzione
- User
Volevo un'implementazione senza che sia necessario allocare ulteriore memoria, è possibile
- Assistant
Sì, è possibile implementare il QuickSort in modo "in-place", senza allocare ulteriore memoria per gli array left, middle e right. Ecco un'implementazione in-place del QuickSort in Python:
def quicksort(arr, low, high): if low < high: pivot_index = partition(arr, low, high) quicksort(arr, low, pivot_index - 1) quicksort(arr, pivot_index + 1, high) def partition(arr, low, high): pivot = arr[high] i = low - 1 for j in range(low, high): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1 arr = [3, 6, 8, 10, 1, 2, 1] print("Array prima del sorting:", arr) quicksort(arr, 0, len(arr) - 1) print("Array dopo il sorting:", arr)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.