1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| def countSort(arr): if max(arr) > len(arr): n = max(arr) + 1 else: n = len(arr) + 1 output = [0 for i in range(n)] count = [0 for i in range(n)] for i in arr: count[i] += 1 for i in range(len(arr)): count[i + 1] += count[i] print(count) for i in range(len(arr)): output[count[arr[i]] - 1] = arr[i] count[arr[i]] -= 1 return (output[:len(arr)])
arr = [5,6,3,2,1,2,0,8,0] ans = countSort(arr) print(ans)
def countSort(arr): n = len(arr) output = [0 for i in range(256)] count = [0 for i in range(256)] ans = ["" for i in range(n)] for i in arr: count[ord(i)] += 1 for i in range(256): count[i] += count[i - 1] for i in range(n): output[count[ord(arr[i])] - 1] = arr[i] count[ord(arr[i])] -= 1 for i in range(len(arr)): ans[i] = output[i] return ans
arr = "wwwrunoobcom" ans = countSort(arr) print("字符数组排序 %s" % ("".join(ans)))
|