Skip to content

Commit

Permalink
Update Array-RadixSort.py
Browse files Browse the repository at this point in the history
  • Loading branch information
itcharge committed Aug 22, 2023
1 parent b706bff commit 409f932
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions Templates/01.Array/Array-RadixSort.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
class Solution:
def radixSort(self, arr):
def radixSort(self, nums: [int]) -> [int]:
# 桶的大小为所有元素的最大位数
size = len(str(max(arr)))

# 从低位到高位依次遍历每一位,以各个数位值为索引,对数组进行按数位排序
size = len(str(max(nums)))
# 从最低位(个位)开始,逐位遍历每一位
for i in range(size):
# 使用一个长度为 10 的桶来存放各个位上的元素
# 定义个数为 10 的桶数组 buckets,每个桶分别代表 0 ~ 9 中的 1 个数字。
buckets = [[] for _ in range(10)]
# 遍历数组元素,根据元素对应位上的值,将其存入对应位的桶中
for num in arr:
# 遍历数组元素,按照每个元素当前位上的数字,将元素放入对应数字的桶中。
for num in nums:
buckets[num // (10 ** i) % 10].append(num)
# 清空原始数组
arr.clear()
# 从桶中依次取出对应元素,并重新加入到原始数组
nums.clear()
# 按照桶的顺序依次取出对应元素,重新加入到原始数组中。
for bucket in buckets:
for num in bucket:
arr.append(num)

return arr

def sortArray(self, nums: List[int]) -> List[int]:
return self.radixSort(nums)
nums.append(num)

# 完成排序,返回结果数组
return nums

def sortArray(self, nums: [int]) -> [int]:
return self.radixSort(nums)

print(Solution().sortArray([692, 924, 969, 503, 871, 704, 542, 436]))

0 comments on commit 409f932

Please sign in to comment.