F11*_*F11 6 c# sorting algorithm
最近我在C#中遇到了一个问题,问题是: - 有三个int数组
ARRAY1 = {88,65,09,888,87}
数组2 = {1,49,921,13,33}
数组2 = {22,44,66,88,110}
现在我必须得到所有这三个数组中最高的5个数组.在c#中最优化的方法是什么?
我能想到的方法是获取一个大小为15的数组并添加所有三个数组的数组元素并对其进行排序.
使用 LINQ 的简单方法:
int[] top5 = array1.Concat(array2).Concat(array3).OrderByDescending(i => i).Take(5).ToArray();
Run Code Online (Sandbox Code Playgroud)
一个最优的方式:
List<int> highests = new List<int>(); // Keep the current top 5 sorted
// Traverse each array. No need to put them together in an int[][]..it's just for simplicity
foreach (int[] array in new int[][] { array1, array2, array3 }) {
foreach (int i in array) {
int index = highests.BinarySearch(i); // where should i be?
if (highests.Count < 5) { // if not 5 yet, add anyway
if (index < 0) {
highests.Insert(~index, i);
} else { //add (duplicate)
highests.Insert(index, i);
}
}
else if (index < 0) { // not in top-5 yet, add
highests.Insert(~index, i);
highests.RemoveAt(0);
} else if (index > 0) { // already in top-5, add (duplicate)
highests.Insert(index, i);
highests.RemoveAt(0);
}
}
}
Run Code Online (Sandbox Code Playgroud)
保留前 5 个排序列表并仅遍历每个数组一次。
您甚至可以每次检查前 5 个中最低的一个,从而避免 BinarySearch:
List<int> highests = new List<int>();
foreach (int[] array in new int[][] { array1, array2, array3 }) {
foreach (int i in array) {
int index = highests.BinarySearch(i);
if (highests.Count < 5) { // if not 5 yet, add anyway
if (index < 0) {
highests.Insert(~index, i);
} else { //add (duplicate)
highests.Insert(index, i);
}
} else if (highests.First() < i) { // if larger than lowest top-5
if (index < 0) { // not in top-5 yet, add
highests.Insert(~index, i);
highests.RemoveAt(0);
} else { // already in top-5, add (duplicate)
highests.Insert(index, i);
highests.RemoveAt(0);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3386 次 |
| 最近记录: |