[英]Better way of inserting numbers into an array while sorting it
Let's say I want to insert values into an array while at the same time sorting it. 假设我想将值插入数组,同时对其进行排序。 This was my solution:
这是我的解决方案:
int[] arr = new int[5];
int k;
arr[0] = int.Parse(Console.ReadLine());
for (int i = 1; i < arr.Length; i++)
{
int num = int.Parse(Console.ReadLine());
for (k = i; k > 0 && num < arr[k - 1];--k) arr[k] = arr[k - 1];
arr[k] = num;
}
I know I didn't handle exceptions, I'm just talking about the code itself. 我知道我没有处理异常,我只是在谈论代码本身。
Is there a better way of doing this? 有更好的方法吗?
You can use a SortedSet<> , that gets automatically sorted as you add items. 您可以使用SortedSet <> ,它会在添加项目时自动排序。
var numbers = new SortedSet<int>()
{
4,
9,
6,
3
};
foreach (var number in numbers)
{
Console.WriteLine(number);
}
If it doesn't have to be array you could do this: 如果不必是数组,则可以执行以下操作:
static void Main(string[] args)
{
List<int> list = new List<int>
{
1,
2,
7,
10
};
int k = int.Parse(Console.ReadLine());
list.Add(k);
list.Sort();
}
Edit: if you want to sort when inserting you could do this: 编辑:如果要在插入时进行排序,可以这样做:
int k = int.Parse(Console.ReadLine());
int i = list.Where(x => x > k).Min();
int index = list.IndexOf(i);
list.Insert(index, k);
You can use a List
and convert it into an array. 您可以使用
List
并将其转换为数组。 When you maintain your list ordered at all time you can use the list's BinarySearch
method to get the insert index: 当您始终保持列表有序时,可以使用列表的
BinarySearch
方法获取插入索引:
const int length = 5;
List<int> result = new List<int>(length);
for (int i = 0; i < length; i++) {
int num = int.Parse(Console.ReadLine());
int insertIndex = result.BinarySearch(num);
if (insertIndex < 0) {
insertIndex = ~insertIndex;
}
result.Insert(insertIndex, num);
}
int[] arr = result.ToArray();
The binary search is much faster than the linear search you are currently performing. 二进制搜索比目前正在执行的线性搜索快得多 。 You won't see that with your current 5 values.
您当前的5个值将看不到。 You would defenitely see it with larger lists (hundrets or thousands of values).
您会通过较大的列表(数百个或数千个值)清楚地看到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.