如何在只更改一个元素的情况下在排序列表中进行快速排序
How to do fast sorting in sorted list when only one element is changed
我需要一个始终排序的元素列表。所涉及的操作非常简单,例如,如果列表从高到低排序,那么在一些循环任务中我只需要三个操作:
while true do {
list.sort() //sort the list that has hundreds of elements
val = list[0] //get the first/maximum value in the list
list.pop_front() //remove the first/maximum element
...//do some work here
list.push_back(new_elem)//insert a new element
list.sort()
}
然而,由于我一次只添加一个elem,并且我有速度问题,所以我不希望排序遍历所有元素,例如,使用气泡排序。所以我只是想知道是否有一个函数可以按顺序插入元素?或者list::sort()函数是否足够聪明,可以在只添加/修改一个元素时使用某种快速排序?或者,如果以上都是需要的操作,我应该使用deque来获得更好的速度性能吗?
非常感谢!
如注释中所述,如果未锁定到std::list
,则应尝试std::set
或std::multiset
。
std::list::insert
方法采用迭代器,该迭代器指定在何处添加新项。您可以使用std::lower_bound
来查找正确的插入点;如果没有随机访问迭代器,它不是最优的,但它仍然只进行O(logn)比较。
附言:不要使用与list
等内置类冲突的变量名。
lst.sort(std::greater<T>()); //sort the list that has hundreds of elements
while true do {
val = lst.front(); //get the first/maximum value in the list
lst.pop_front(); //remove the first/maximum element
...//do some work here
std::list<T>::iterator it = std::lower_bound(lst.begin(), lst.end(), std::greater<T>());
lst.insert(it, new_elem); //insert a new element
// lst is already sorted
}
相关文章:
- 如何在不C++排序的情况下找到给定向量中的第一、第二和第三高值?
- C++数组与向量排序(在我的情况下,向量比数组慢~2.5倍(无优化))
- 类(可能是代理)的命名,允许在不修改基础容器的情况下对项目进行排序和删除
- c++ 选择排序在特定情况下不起作用
- 在不进行排序的情况下查找数组中n个最小值的索引
- 在最坏的情况下试验快速排序.它运行良好,但在最坏的情况下发生未知错误.我想
- 如何在不通过插入排序更改原始矢量的情况下对 2D 矢量进行排序
- 如何在不使用标准算法的情况下在排序向量中添加 c 元素?
- 如何在没有 c++ 中的数组/算法的情况下对两个条件的字符串进行排序
- 我可以使用 std::sort 对 C 样式数组(在我的结构情况下)进行排序吗?
- 特征在不复制的情况下对行重新排序
- 在不使用默认算法的情况下对字符串的 std 向量进行排序
- 在某些情况下,我的快速排序实现失败
- 在给定两个排序向量的情况下设置减法
- 在每种情况下都执行“std::set”对元素进行排序
- 如何在不使用循环的情况下进行排序
- 如何在只更改一个元素的情况下在排序列表中进行快速排序
- 在不知道输入大小的情况下对字符串 c++ 向量进行排序
- 在不使用数组的情况下对二进制文件中的数据进行排序
- 在不进行冒泡排序的情况下,计算数组中冒泡排序交换的次数