-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy path计数排序算法.cs
64 lines (52 loc) · 1.87 KB
/
计数排序算法.cs
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
namespace HelloDotNetGuide.常见算法
{
public class 计数排序算法
{
public static void CountingSort(int[] array)
{
int arrayLength = array.Length;
if (arrayLength <= 1) return;
int min = array[0];
int max = array[0];
//找出最大值和最小值
for (int i = 1; i < arrayLength; i++)
{
if (array[i] < min) min = array[i];
if (array[i] > max) max = array[i];
}
//统计每个元素出现的次数
int[] count = new int[max - min + 1];
//统计每个元素出现的次数
for (int i = 0; i < arrayLength; i++)
{
count[array[i] - min]++;
}
//根据count数组和min值确定每个元素的起始位置
for (int i = 1; i < count.Length; i++)
{
count[i] += count[i - 1];
}
//存储排序结果
int[] temp = new int[arrayLength];
//根据count数组和min值确定每个元素在temp数组中的位置
for (int i = arrayLength - 1; i >= 0; i--)
{
int index = count[array[i] - min] - 1;
temp[index] = array[i];
count[array[i] - min]--;
}
//将排序结果复制回原数组
for (int i = 0; i < arrayLength; i++)
{
array[i] = temp[i];
}
}
public static void CountingSortRun()
{
int[] array = { 19, 27, 46, 48, 50, 2, 4, 44, 47, 36, 38, 15, 26, 5, 3, 99, 888 };
Console.WriteLine("排序前数组:" + string.Join(", ", array));
CountingSort(array);
Console.WriteLine("排序后数组:" + string.Join(", ", array));
}
}
}