# %%
from typing import List
class Solution:
"""The main class for program. It's meaningless.
"""
def quick_sort(self,
arr: List[int],
ascending=True
):
"""The implements of recursion.
Input:
arr: The input array contains integer numbers. (Need Checks)
ascending: It determines the order of output arrays (defalut ascending)
Output:
1. An integer array in order.
"""
# Checks
if arr is None:
raise Exception("The paramer arr is None.")
# If arr contains non-integer numbers.
for i in arr:
if not isinstance(i, int):
raise Exception("The array contains non-integer number.")
# If the number of elements more than 2*30.
if len(arr) > 2**30:
raise Exception(
"The array is too long. Please change other algorithims.")
# If the number of elements less than two.
if len(arr) < 2:
return arr
# Check Done!
def quick_sort_recursion(arr, low, high):
"""Implements recursion.
"""
# Recurison return point.
if low >= high:
return
# The left of the index pi is smaller than or equal to arr[pi].
# The right of the index pi is greater than or equal to arr[pi].
pi = partition(arr, low, high)
# Before pi
quick_sort_recursion(arr, low, pi-1)
# After pi
quick_sort_recursion(arr, pi+1, high)
def partition(arr, low, high) -> int:
"""This function always takes the last element as the pivot and places the elements(smaller than arr[pi]) to
the left of pi, and places the elements(greater than arr[pi]) to the right of pi. Then return the index of pi.
"""
# Base number
piovt = arr[high]
# The index of smaller element
smaller_index = (low - 1)
# The traverse, For arr[j], jumps the elements(greater than pivot).
for i in range(low, high):
# If find element( smaller than pivot or equal to pivot). Exchange arr[j] and arr[i](arr[i] is greater than pivot at this moment.)
if arr[i] <= piovt:
smaller_index += 1
arr[smaller_index], arr[i] = arr[i], arr[smaller_index]
# handel the pivot.
arr[high], arr[smaller_index+1] = arr[smaller_index+1], arr[high]
return (smaller_index+1)
# Avaid to influence the arr itself.
# Copy arr
temp = arr[:]
quick_sort_recursion(temp, 0, len(temp)-1)
if ascending:
return temp
else:
# Reverse
return temp[::-1]
if __name__ == "__main__":
test_data1 = [0, 10, 15, 9, 8, 1, 6, 8, 10]
h = Solution()
print("Ascending: ", h.quick_sort(test_data1))
print("Decending: ", h.quick_sort(test_data1, ascending=False))
print("row test data: ", test_data1)