class QuickSortExample:
def __init__(self):
pass
def quickSort(self, arr, low, high):
if(low < high):
# Find the pivot index of the lower bound of an array
pivot = self.partition(arr, low, high)
# Apply Divide and conquer strategy
# to sort the left side and right side of an array
# respective to the pivot position
# Left hand side array
self.quickSort(arr, low, pivot - 1)
#Right hand side array
self.quickSort(arr, pivot + 1, high)
return arr
def partition(self, arr, low, high):
# Pick a lowest bound element as an pivot value
pivot = arr[low]
i = low
j = high
while(i < j):
# Increment the index value (i.e. i )
# till the piovt value is greater than or equal the left most values
while(arr[i] <= pivot and i < high):
i += 1
# Increment the index value (i.e. j )
# till the piovt value is less than the right most values
while(arr[j] > pivot and j > low):
j -= 1
# Interchange the values of present
# in the index i and j of an array only if i is less than j
if(i < j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
# Interchange the element in j's poisition to the lower bound of an array
# and place the Pivot element to the j's position
arr[low] = arr[j]
arr[j] = pivot
return j
def printArray(self, arr):
# Loop the item and print each item in the console with white space seperated
string = " ".join([str(item) for item in arr])
print(string)
obj = QuickSortExample()
arr = [15, 3, 12, 6, -9, 9, 0]
print("Before Sorting: ")
obj.printArray(arr)
result = obj.quickSort(arr, 0, len(arr) - 1)
print("After Sorting: ")
obj.printArray(result)
输出
Before Sorting:
15 3 12 6 -9 9 0
After Sorting:
-9 0 3 6 9 12 15