Quicksort Python [geschlossen]Python

Python-Programme
Anonymous
 Quicksort Python [geschlossen]

Post by Anonymous »

Ich weiß einfach nicht, wo es mit meinem Code schief geht. Ich versuche, die Quicksort -Methode zu verwenden, um ein Array in aufsteigender Reihenfolge zu sortieren, scheint nicht zu funktionieren. < /P>

Code: Select all

def quicksort(array, left, right):
if left < right:
pivot = partition(array, left, right)
quicksort(array, left, pivot - 1)
quicksort(array, pivot + 1, right)
return array

def partition(array, left, right): #left and right are indices
#pick the pivot as the middle element
pivot = array[round((left + right)/2)]
while left < right:
while array[left] < pivot:
left += 1
while array[right] > pivot:
right -= 1
if left < right:
# swap the 2 elements
array[left], array[right] = array[right], array[left]
left += 1
right -= 1

# swap the pivot and the last element (where the 2 pointers meet each other)
array[left], array[array.index(pivot)] = array[array.index(pivot)], array[left]
return left
< /code>

Wenn < /p>

print(quicksort([4, 6, 8, 1, 3], 0, 4))
< /code>

Das Ergebnis ist < /p>

[3, 4, 6, 1, 8]

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post