|
| 1 | +import collections |
| 2 | +import sys |
| 3 | +import random |
| 4 | +import time |
| 5 | +import math |
| 6 | +""" |
| 7 | +A python implementation of the quick select algorithm, which is efficient for calculating the value that would appear in the index of a list if it would be sorted, even if it is not already sorted |
| 8 | +https://en.wikipedia.org/wiki/Quickselect |
| 9 | +""" |
| 10 | +def _partition(data, pivot): |
| 11 | + """ |
| 12 | + Three way partition the data into smaller, equal and greater lists, |
| 13 | + in relationship to the pivot |
| 14 | + :param data: The data to be sorted (a list) |
| 15 | + :param pivot: The value to partition the data on |
| 16 | + :return: Three list: smaller, equal and greater |
| 17 | + """ |
| 18 | + less, equal, greater = [], [], [] |
| 19 | + for element in data: |
| 20 | + if element.address < pivot.address: |
| 21 | + less.append(element) |
| 22 | + elif element.address > pivot.address: |
| 23 | + greater.append(element) |
| 24 | + else: |
| 25 | + equal.append(element) |
| 26 | + return less, equal, greater |
| 27 | + |
| 28 | + def quickSelect(list, k): |
| 29 | + #k = len(list) // 2 when trying to find the median (index that value would be when list is sorted) |
| 30 | + smaller = [] |
| 31 | + larger = [] |
| 32 | + pivot = random.randint(0, len(list) - 1) |
| 33 | + pivot = list[pivot] |
| 34 | + count = 0 |
| 35 | + smaller, equal, larger =_partition(list, pivot) |
| 36 | + count = len(equal) |
| 37 | + m = len(smaller) |
| 38 | + |
| 39 | + #k is the pivot |
| 40 | + if m <= k < m + count: |
| 41 | + return pivot |
| 42 | + # must be in smaller |
| 43 | + elif m > k: |
| 44 | + return quickSelect(smaller, k) |
| 45 | + #must be in larger |
| 46 | + else: |
| 47 | + return quickSelect(larger, k - (m + count)) |
0 commit comments