I am trying to perform a quicksort on Python where it pulls a random integer instead of the first element and compares values from the left and right and sorts as such. My partition and quicksort methods already work (I've tested and it sorted), but I can't figure out what to do for taking a random int first.
So far, I've imported my random package and tried something called "random.choice()". The problem is this only takes the first element rather than all of them. Afterwards, I need to call to partition (as implemented on quicksort. One last part, I need to use the following pseudocode:
if (numItemsInSubArray > 16) then swap a[low] and a[random index between high and low];
I'll post my code below, any thoughts will help, thanks.
def quicksort3(array, low, high):
if high > low:
index = partition(array, low, high)
quicksort3(array, low, index - 1)
quicksort3(array, index + 1, high)
# attempt to return first element in array, followed by quicksorted array
random.choice(array)
if (len(subarray) > 16):
# swap a[low] and a[random index (such as high?) between high and low];
array[low], array[high] = array[high], array[low]
def partition(array, low, high):
firstitem = array[low]
j = low
for i in range(low+1, high+1):
if array[i] < firstitem:
j+=1
array[j], array[i] = array[i], array[j]
index = j
array[low], array[index] = array[index], array[low]
return index
array = [10, 3, 4, 8, 1, 7, 0, 13]
quicksort3(array, 0, len(array)-1)
for j in range(len(array)):
print ("%d" %array[j])
Aucun commentaire:
Enregistrer un commentaire