https://leetcode-cn.com/submissions/detail/24102019/
class Solution(object):
def sortArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# ------------------------------------------------------------------------
def countingSort(data):
# 1 得到数列的最大值和最小值,并计算差值
maxNum, minNum = max(data), min(data)
d = maxNum - minNum
if data == [] or d == 0: return data
# 2 创建统计数组,并统计对应元素的个数
countingArray = [0]*(d+1)
for i in data:
countingArray[i-minNum] += 1
# 3 统计数组做变形,后面的元素等于前面的元素之和,让统计数组存储的元素值,等于相应整数的最终排序位置。
for i in range(1, len(countingArray)):
countingArray[i] = countingArray[i] + countingArray[i-1]
# 4 倒序遍历元素数组,从统计数组找出正确位置,输出到结果数组
sortedArray = [0]*len(data)
for i in reversed(range(0, len(data))):
sortedArray[countingArray[data[i] - minNum] - 1] = data[i]
countingArray[data[i] - minNum] -= 1
return sortedArray
# ------------------------------------------------------------------------
return countingSort(nums)
#include<stdio.h>
#include<malloc.h>
#define MAXNUM 1000
//***************************************************计数排序*************************************
void Counting_Sort(int A[], int n)
{
int *Bucket = (int *)malloc(sizeof(int)*MAXNUM); //可以 int Bucket[MAXNUM]
int *Result = (int *)malloc(sizeof(int)*n); //不能 int Result[n],n没确定
for (int i = 0; i < MAXNUM; i++) //把1000个桶初始化
Bucket[i] = 0;
for (i = 0; i < n; i++)
Bucket[A[i]] ++; // Bucket[A[i]]---值=A[i]的个数
for (i = 1; i < MAXNUM; i++)
Bucket[i] = Bucket[i - 1] + Bucket[i]; //Bucket[i]---值<=i的个数
for (i = n - 1; i >= 0; i--)
Result[--Bucket[A[i]] ] = A[i]; //排序
for (i = 0; i < n; i++)
A[i] = Result[i]; //输出到原始数组
free(Bucket);
free(Result);
}
void main()
{
int n;
printf("请输入待排序的个数:");
scanf("%d",&n);
int *A = (int *)malloc(sizeof(int)*n);
printf("输入排序前:\n");
for (int i = 0; i < n; i++)
scanf("%d",&A[i]);
Counting_Sort(A,n);
printf("输出排序后:\n");
for (i = 0; i < n; i++)
printf("%d ", A[i]); //等价于 *(A+i)
getchar();getchar();
}