Skip to content

Instantly share code, notes, and snippets.

@davidejones
Last active August 31, 2016 16:20
Show Gist options
  • Select an option

  • Save davidejones/2bb9c3df730aaaa3e3c7a7406f264572 to your computer and use it in GitHub Desktop.

Select an option

Save davidejones/2bb9c3df730aaaa3e3c7a7406f264572 to your computer and use it in GitHub Desktop.
first attempt at a quick sort
def quick_sort(l, start=None, end=None):
# get the length of our working list
list_len = len(l[start:end])
# if this is the first iteration end is length of whole list
end = len(l) if end is None else end
# choose the last item of working list as pivot
pivot = l[end-1]
# set wall left of first element in working list
wall_index = start-1 if start is not None else -1
# set the current element we start with to after wall (first element in working list)
current_element = l[wall_index+1]
# count iterations starting with 0 or start with working list start
count = start if start is not None else 0
while current_element != pivot:
if current_element < pivot:
# swap current element with index just right of the wall
l[count], l[wall_index + 1] = l[wall_index + 1], l[count]
# now move the wall
wall_index += 1
count += 1
# move pointer to next element
current_element = l[count]
# swap pivot with first element on right side of wall as we know that's its rightful place
l[end - 1], l[wall_index + 1] = l[wall_index + 1], l[end-1]
# now pass the left into quick_sort again if we have more than 1 element
if len(l[start:wall_index + 2]) > 1:
quick_sort(l, None, wall_index + 1)
# now pass the right into quick_sort again if we have more than 1 element
if len(l[wall_index + 1:end]) > 1:
# note + 2 as we don't want to pass in this iterations pivot as its in correct position
quick_sort(l, wall_index + 2, None)
if __name__ == '__main__':
my_list = [1, 12, 4, 7, 3, 5, 2, 6, 11, 10, 9, 13, 8]
quick_sort(my_list)
print(my_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment