我编写了一个程序,它从用户界面获取一个数字数组(自然数)并将它们注入动态分配的数组中。 我在计算程序的大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;
}
答案 0 :(得分:2)
总复杂度为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;
}