for part of my homework I need to convert this quicksort code into a class. (I have other sorting algorithms to convert, heapsort,mergesort,bubblesort,etc, but helping with this one example will help me with the others)
Inside the class I need to count the number of array operations performed, and the recursive calls (I assume this would be a counter inside of the init)
I also need to count the number of extra array spaces allocated when performing the algorithm.
I'm not asking to fully finish the class with the above specs completed, all I'm asking is for someone to help me with the creation of the class in order to fulfill the specs, I can figure out where/when to add to the arrayoperations/extra array space counters.
from random import *
def partition(array,first,last) :
print("first:",first,"last:",last)
big = first + 1
small = last
pivot = array[first]
while (big <= small) :
while (big <= last and array[big] <= pivot) :
big += 1
while array[small] > pivot :
small -= 1
if big < small :
array[small], array[big] = array[big], array[small]
array[first], array[small] = array[small], array[first]
return small
def quickSort(array,first,last) :
if first >= last :
return
pivLoc = partition(array,first,last)
quickSort(array, first, pivLoc-1)
quickSort(array, pivLoc+1, last)
return
An arbitrary set of functions can become class methods by enclosing them just like so:
class ClassName:
def __init__(self):
pass
... # Functions go here
Of course this is not super useful, but here's how it would look with your code.
class QuickSorter:
def __init__(self):
pass
def partition(array,first,last) :
print("first:",first,"last:",last)
big = first + 1
small = last
pivot = array[first]
while (big <= small) :
while (big <= last and array[big] <= pivot) :
big += 1
while array[small] > pivot :
small -= 1
if big < small :
array[small], array[big] = array[big], array[small]
array[first], array[small] = array[small], array[first]
return small
def quickSort(array,first,last) :
if first >= last :
return
pivLoc = partition(array,first,last)
quickSort(array, first, pivLoc-1)
quickSort(array, pivLoc+1, last)
return
But you often want some data members so your methods can share data. (This is how you track the metrics your professor asked for.)
class Stack:
def __init__(self, array):
self.array = []
def push(self, new):
self.array = self.array + [new]
...