Skip to content

Instantly share code, notes, and snippets.

@liyunrui
Last active July 8, 2021 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liyunrui/cb93a1800811d456d3a3f647bf336a7f to your computer and use it in GitHub Desktop.
Save liyunrui/cb93a1800811d456d3a3f647bf336a7f to your computer and use it in GitHub Desktop.
leetcode-sorting
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
return self.bucketSort(nums)
def bucketSort(self, A):
"""
1. It's in-place sorting.
2. Bucket sort is mainly useful when input is uniformly distributed over a range.(floating number is allowed)
step1: create n buckets
step2: put element into buckets
step3: 依序處理所有非空的桶子
ref:https://www.geeksforgeeks.org/bucket-sort-2/?ref=lbp
Average case, O(n+k)
Worst case, every element was put into same bucket. Insertion sort might take O(n^2)
"""
n = len(A)
buckets = [[] for _ in range(n)]
mini = min(A)
maxi = max(A)
rang = maxi-mini
# edge case
if rang == 0:
return A
# O(n), in below way, put val into bucekt in order.
# This step also takes O(n) time on average if all numbers are uniformly distributed
for a in A:
# index shoude be 0 to n-1
i = int ( (a-mini) * (n-1) / rang )
buckets[i].append(a)
#O(k+n), where k is nb of non-empty buckets, we need to process n elements.
i=0
for b in buckets:
# each bucket has the size O(1), so sorting is O(1) too
b.sort(reverse=True) # decending
while b:
A[i] = b.pop()
i += 1
return A
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment