def partition(lst, start, end): middle_value = lst[end] middle_index = start - 1 for index in range(start, end): if lst[index] <= middle_value: middle_index += 1 swap(lst, middle_index, index) middle_index += 1 swap(lst, middle_index, end) return middle_index
def partition(lst, median_value): """divide lst by median_value and return the index of median_value""" middle_index = -1 for i in range(len(lst)): if lst[i] <= median_value: middle_index += 1 swap(lst, middle_index, i) if lst[middle_index] == median_value: self_index = middle_index swap(lst, middle_index, self_index) return middle_index
def radix_sort(lst): """sorting a word list to dict-order""" # get the length of the longest word longest_length = 0 if len(lst) < 0: return for i in range(len(lst)): if len(lst[i]) > longest_length: longest_length = len(lst[i]) # sorting for i in range(longest_length - 1, -1, -1): # using any stable sorting algo, for example bubble sort for x in range(1, len(lst)): for y in range(len(lst) - x): if get_alphabet(lst, y) > get_alphabet(lst, y + 1): swap(lst, y, y + 1)
def quick_sort(lst, start=0, end=-1): if end == -1: end = len(lst) - 1 if start < end: exchange_index = start - 1 # randomized middle value middle_index = np.random.randint(start, end) swap(lst, middle_index, end) for i in range(start, end): if lst[i] <= lst[end]: exchange_index += 1 swap(lst, i, exchange_index) exchange_index += 1 swap(lst, end, exchange_index) if start < exchange_index: quick_sort(lst, start, exchange_index-1) if exchange_index < end: quick_sort(lst, exchange_index+1, end)
def randomized_partition(lst, start, end): middle = np.random.randint(start, end) swap(lst, middle, end) return partition(lst, start, end)