如何在只更改一个元素的情况下在排序列表中进行快速排序

How to do fast sorting in sorted list when only one element is changed

本文关键字:排序 情况下 列表 快速排序 元素 一个      更新时间:2023-10-16

我需要一个始终排序的元素列表。所涉及的操作非常简单,例如,如果列表从高到低排序,那么在一些循环任务中我只需要三个操作:

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::setstd::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
}
相关文章: