Skip to content

Instantly share code, notes, and snippets.

@raeq
Last active May 14, 2018 14:50
Show Gist options
  • Select an option

  • Save raeq/68772764acb1502be8cb6dd66f56dedf to your computer and use it in GitHub Desktop.

Select an option

Save raeq/68772764acb1502be8cb6dd66f56dedf to your computer and use it in GitHub Desktop.
A small python function to quicksort any list from smallest to largest. Now using the correct division operator "//".
def quicksort(p_list):
"""
Quicksort using comprehension and recursion on a list.
"""
if len(p_list) < 1:
return p_list
center = p_list[len(p_list) // 2]
centers = [x for x in p_list if x == center]
smaller = quicksort([x for x in p_list if x < center])
larger = quicksort([x for x in p_list if x > center])
return smaller + centers + larger
def main():
nums = [14, 567, 3345, 34553, 2454, 29, 55, 6, 87, 123, 21312, 199,
546, 568, 78, 987, 234234, 15, 7, 657, 25, 2, 234, 64, 35, 6544, 1]
print (quicksort(nums))
pass
if __name__ == '__main__':
main()
@RyukGremory

RyukGremory commented May 11, 2018

Copy link
Copy Markdown

You need to convert
center=p_list[len(p_list)/2]
to
center=p_list[int(len(p_list)/2)]

You need to convert the center to int.
List indices must be integers or slices, not float. Your code give an error, because when you divide a number the result has a decimal point.

@raeq

raeq commented May 14, 2018

Copy link
Copy Markdown
Author

@RyukGremory Thank you!
Your observation is correct for Python3.x I developed this in Python2.7 and it works fine there :)

The explanation is that Python3 uses "/" as a float division, Python2 uses "/" as an integer division. Your suggested change would make the code work in both versions.

Using // is better I think. The intent is to force an integer division, regardless of the Python version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment