算法的复杂性,包括动态分配的数组
Complexity of algorithm including dynamically allocated array
我写了一个程序,从用户界面获得一个数字数组(自然数),并将它们注入到一个动态分配的数组中。我一直在计算程序的big-O,非常感谢您帮助我评估它。我的猜测是O(nlogn),但我不知道如何证明。
代码:
int* gradesToArr(int& arr_size, int& numOfGrades) //function that gets parameters of initial array size (array for array of numbers received from user), and actual amount of numbers that been received.
{
int input, counter = 0;
arr_size = 2;
int* arr = new int[arr_size]; //memory allocation for initial array for the sake of interface input.
do { //loop for getting and injecting numbers from the user interface right into the Array arr.
if (counter < arr_size)
{
cin >> input;
if (input != -1)
{
arr[counter] = input;
counter++;
}
}
else
arr = allocateArr(arr, arr_size); //in case of out-of-memory, calling the function "allocateArr" that allocates twice larger memory for arr.
} while (input != -1);
numOfGrades = counter; //update the size of numOfGrades that indicates the amount of grades received from user and inserted to the array.
return arr;
}
int* allocateArr(int Arr[], int &size) //function that allocates bigger array in case of out-of-memory for current quantity of elements.
{
int* fin;
fin = new int[size * 2]; //allocates twice more space then been before
for (int i = 0; i < size; i++) //copies the previous smaller array to the new bigger array
fin[i] = Arr[i];
delete[]Arr; //freeing memory of Arr because of no need, because the data from Arr moved to fin.
size *= 2;
return fin;
}
总复杂度为O(n)
。您将得到O(log(n))
内存分配,您可能会认为,每个内存分配都会得到O(n)
操作。但事实并非如此,因为在第一次迭代中,您所做的操作数量要少得多。大部分工作都是临摹。上次复制时,您的复制操作少于n
。您的复制操作少于n/2
之前的时间。进行n/4
复制操作之前的时间,依此类推。这总计为
n + n/2 + n/4 + ... + 2 < 2*n
单个数组元素的副本。因此,你有
O(2*n) = O(n)
操作总数。
简化代码
您基本上手动实现了std::vector
的内存管理。这会使代码变得不必要的复杂。只需使用std::vector
,就可以获得相同的性能,但出错的风险较小。像这样:
#include <vector>
#include <iostream>
// reads grades from standard input until -1 is given and
// returns the read numbers (without the -1).
std::vector<int> gradesToArr()
{
std::vector<int> result;
for(;;)
{
int input = 0;
std::cin >> input;
if ( input == -1 )
break;
result.push_back(input);
}
return result;
}
相关文章:
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 动态更改数组的大小并读取值.(无矢量)
- 检测到堆损坏:在正常块 c++ 动态 2D 数组之后
- 动态维度数组的 C++ 别名指针
- C++ 在析构函数调用之前删除的动态成员数组
- 从类 c++ 动态创建数组
- 具有静态 std::array 的神经网络比使用动态 C 数组的神经网络慢
- "Error reading character of string" 为哈希动态增长数组的问题 (C++)
- 为什么我们在传递动态 2D 数组时不需要列数?
- 如何解决在使用动态 2D 数组进行矩阵乘法的 MPI 进行并行编程时的问题
- 使用动态布尔数组时出现问题
- C++ 在类中删除动态 2D 数组时不断"Aborted (core dumped)"
- 如何在C 中动态输入数组
- 关于删除动态对象数组
- 在C 中动态更改数组大小
- 使用动态指针数组进行动态对象分配 - 使用什么删除?
- 动态字符串数组分配错误
- 函数中的动态 2D 数组分配并将其返回给主数组
- c++动态字符串数组分配
- 使用字符串或字符动态分配(数组)