假设有一百万个介于1到9之间的整数,请问您如何以有效的方式将它们进行排序?
Input: [1,2,5,4,7,8,9,6,5,4,2,3,6,5,8]
Output: [1,2,2,3,4,4,5,5,5,6,6,7,8,8,9]
假设有一百万个介于1到9之间的整数,请问您如何以有效的方式将它们进行排序?
Input: [1,2,5,4,7,8,9,6,5,4,2,3,6,5,8]
Output: [1,2,2,3,4,4,5,5,5,6,6,7,8,8,9]
Collections.sort()
使用TimSort算法,它的时间复杂度为O(n log(n))。
如果你想让它运行得更快,比如线性时间,那么你应该使用基于非比较的排序算法。k=9
(范围为1-9),N=1000000
,那么你的运行时间将是O(k + N)。输入:[1,2,5,4,7,8,9,6,5,4,2,3,6,5,8]
输出:[1,2,2,3,4,4,5,5,5,6,6,7,8,8,9]
这可以在O(n)时间内使用O(k)空间解决。
由于给定范围为9,因此我们可以创建一个大小为9 + 1的数组,其中每个索引将存储输入数组中数字的出现次数。
TempArray = [0 1 2 1 2 3 2 1 2 1] Index 0 1 2 3 4 5 6 7 8 9
您只需要读取tempArray并将数据填充回输入即可。
索引1处的值为1,因此我们只会添加一个元素。
索引2处的值为2,因此我们会添加两次数字2。
索引3处的值为1,因此我们只会添加三次。
索引4处的值为2,因此我们只会将4添加两次。
通过这种方式,您可以覆盖原始数组。
T(O(n))
S(O(k))
如果有任何困惑,请告诉我。
以下是相应的C#代码:
int[] input = new int[15] { 1, 2, 5, 4, 7, 8, 9, 6, 5, 4, 2, 3, 6, 5, 8 };
int k = 9;
int[] temp = new int[k + 1];
for (int index = 0; index < input.Length; index++)
{
temp[input[index]]++;
}
int i = 0; // used for input index
for (int index = 0; index < temp.Length; index++)
{
while (temp[index]-- != 0) // redusing count value after updating the index into input array
input[i++] = index;
}
for (int index = 0; index < input.Length; index++)
{
Console.Write(" {0} ", input[index]);
}