Counting sort

本文详细介绍了计数排序算法的工作原理及其实现过程。通过两个不同的代码片段展示了如何处理非负整数排序及包含负数的情况,并解释了为什么计数排序的时间复杂度为O(n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The running time of counting sort is O(n), and usually, the running time of sorting algorithms will be either O(n^2) or O(n lgn), the reason why counting sort is O(n) is that it doesn't have the comparison.In fact, the sorting is hidden from line 19 to line 27.

class CountingSortAlgorithm { public void CountingSort(int[] arrayA) { int max = arrayA[0]; for (int i = 1; i < arrayA.Length; i++) { if (arrayA[i] > max) { max = arrayA[i]; } } int[] arrayC = new int[max + 1]; int[] arrayB = new int[arrayA.Length]; for (int i = 0; i < arrayA.Length; i++) { arrayC[arrayA[i]] += 1; } for (int i = 1; i < arrayC.Length; i++) { arrayC[i] += arrayC[i - 1]; } for (int i = arrayA.Length - 1; i >= 0; i--) { arrayB[arrayC[arrayA[i]] - 1] = arrayA[i]; arrayC[arrayA[i]]--; } for (int i = 0; i < arrayA.Length; i++) { arrayA[i] = arrayB[i]; } } }

The code segment above is only suitable for the case in which all the elements in the array are non-negative. If the array

has negative element, we can simply 'shift' the element, such as the minimum element will be considered as 0. I use 'span'

to shift the element.

class CountingSortAlgorithm { public void CountingSort(int[] arrayA) { int max = arrayA[0]; int min = arrayA[0]; for (int i = 1; i < arrayA.Length; i++) { if (arrayA[i] > max) { max = arrayA[i]; } if (arrayA[i] < min) { min = arrayA[i]; } } int span = -min; int[] arrayC = new int[max - min + 1]; int[] arrayB = new int[arrayA.Length]; for (int i = 0; i < arrayA.Length; i++) { arrayC[arrayA[i] + span] += 1; } for (int i = 1; i < arrayC.Length; i++) { arrayC[i] += arrayC[i - 1]; } for (int i = arrayA.Length - 1; i >= 0; i--) { arrayB[arrayC[arrayA[i] + span] - 1] = arrayA[i]; arrayC[arrayA[i] + span]--; } for (int i = 0; i < arrayA.Length; i++) { arrayA[i] = arrayB[i]; } } }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值