Created
August 27, 2023 12:58
-
-
Save paulfrische/61b1a62afa7dc4a737fe69f3a9d98857 to your computer and use it in GitHub Desktop.
quick and dirty quick sort in python
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
| import random | |
| def quick_sort(arr): | |
| if len(arr) <= 1: | |
| return arr | |
| pivot = arr[-1] | |
| pivot_index = len(arr) - 1 | |
| i = -1 | |
| for j in range(pivot_index + 1): | |
| # check if value at j < pivot | |
| # if true then: inc i by 1 and swap (i, j) | |
| if arr[j] < pivot: | |
| i += 1 | |
| tmp = arr[i] | |
| arr[i] = arr[j] | |
| arr[j] = tmp | |
| if j == pivot_index: | |
| i += 1 | |
| tmp = arr[i] | |
| arr[i] = arr[j] | |
| arr[j] = tmp | |
| pivot_index = i | |
| lhs = arr[:pivot_index] | |
| rhs = arr[pivot_index + 1:] | |
| return [*quick_sort(lhs), pivot, *quick_sort(rhs)] | |
| numbers = [random.randint(0, 10_000) for _ in range(100)] | |
| print(f'before: {numbers}') | |
| numbers = quick_sort(numbers) | |
| print(f'after: {numbers}') | |
| if numbers != sorted(numbers): | |
| print('UNSORTED') | |
| else: | |
| print('SORTED') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment