提高插入排序的运行时复杂性

Improving run time complexity of insert sort?

本文关键字:运行时 复杂性 插入排序      更新时间:2023-10-16

我编写了以下代码来尝试在 O(log n) 运行时中执行插入到排序向量中:

std::vector<int> to_insert_sort {2,3,5,6,1,1,3,2};
int to_insert {3};
std::sort(to_insert_sort.begin(), to_insert_sort.end()); //O(log n)
auto pos = std::upper_bound(to_insert_sort.begin(), to_insert_sort.end(), 5); //O(log n)
to_insert_sort.insert(pos, to_insert); //O(n)

1)我说这个操作是O(log n)是对的吗?

2) 是否有办法以更高的运行时效率执行此操作?

1)我说这个操作是O(log n)是对的吗?

std::sort O(n * log n)

std::upper_bound O(log n)

std::vector.insert O(n)

2) 是否有办法在增加运行时间的情况下执行此操作 效率?

是的,您可以插入 O(log n),但您需要更改数据结构。例如,您可以使用 std::multiset<int> 而不是 std::vector<int>

std::multiset<int> m;
//m<={2,3,5,6,1,1,3,2}; //O(n * log n)
int to_insert {3};
m.insert(to_insert); //O(log n)