Last active
May 14, 2018 14:50
-
-
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 "//".
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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.