Fastest way to sort in Python

Viewed 61002

What is the fastest way to sort an array of whole integers bigger than 0 and less than 100000 in Python? But not using the built in functions like sort.

Im looking at the possibility to combine 2 sport functions depending on input size.

10 Answers

Bucket sort with bucket size = 1. Memory is O(m) where m = the range of values being sorted. Running time is O(n) where n = the number of items being sorted. When the integer type used to record counts is bounded, this approach will fail if any value appears more than MAXINT times.

def sort(items):
  seen = [0] * 100000
  for item in items:
    seen[item] += 1
  index = 0
  for value, count in enumerate(seen):
    for _ in range(count):
      items[index] = value
      index += 1
Related