[英]What's the most efficient way to insert an element into a sorted vector?
I have a sorted v: Vec<EventHandler<T>>
and I want to insert an element into it while keeping it sorted. 我有一个排序的
v: Vec<EventHandler<T>>
,我想在其中插入元素同时保持其排序。 What's the most efficient way to do so? 这样做最有效的方法是什么? Rust doesn't seem to have a built-in way to do it.
Rust似乎没有内置的方法。
EventHandler<T>
is as follows: EventHandler<T>
如下:
struct EventHandler<T: Event + ?Sized> {
priority: i32,
f: fn(&mut T),
}
Because of how sorting works, inserting and sorting would be inefficient, with O(n log n)
time complexity and 2*n
allocation cost . 由于排序的工作方式,插入和排序效率很低, 时间复杂度为
O(n log n)
,分配成本为2*n
。
The task consists of two steps: finding the insert-position with binary_search
and inserting with Vec::insert()
: 该任务包括两个步骤:使用
binary_search
查找插入位置,并使用Vec::insert()
:
match v.binary_search(&new_elem) {
Ok(pos) => {} // element already in vector @ `pos`
Err(pos) => v.insert(pos, new_elem),
}
If you want to allow duplicate elements in your vector and thus want to insert already existing elements, you can write it even shorter: 如果要在向量中允许重复元素,从而要插入已经存在的元素,则可以将其写得更短:
let pos = v.binary_search(&new_elem).unwrap_or_else(|e| e);
v.insert(pos, new_elem);
But : be aware that this has a runtime complexity of O(n). 但是 :请注意,这具有O(n)的运行时复杂度。 To insert into the middle, the vector has to move every element right of your insert-position one to the right.
要插入到中间,向量必须将插入位置的每个元素向右移动一个。
So you shouldn't use it to insert more than a few elements into a vector, which isn't tiny in size. 因此,您不应该使用它在向量中插入多个元素,向量的大小并不小。 Particularly, you shouldn't use this method to sort a vector, as this insertion sort algorithm runs in O(n²).
特别是,您不应使用此方法对向量进行排序,因为此插入排序算法在O(n²)中运行。
A BinaryHeap
might be a better choice in such a situation. 在这种情况下,
BinaryHeap
可能是更好的选择。 Each insert ( push
) has a runtime complexity of just O(log n) instead of O(n). 每个insert(
push
)的运行时复杂度仅为O(log n)而不是O(n)。 You can even convert it into a sorted Vec
with into_sorted_vec()
, if you so desire. 如果愿意,您甚至可以使用
into_sorted_vec()
将其转换为排序的Vec
。 You can also continue to use the heap instead of converting it. 您还可以继续使用堆而不是对其进行转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.