这是我程序中最重要的部分(数据在一个用逗号分隔的2列文本文件中(例如3,12),第一列值代表权重,第二列代表利润)此方法填充从文本文件中的数据中获取大小为n的struct(struct有2个字段的权重和利润)数组,然后根据我的比较方法对项目进行排序,如下所示。
static void Read(ref Items[] Item)
{
string[] lines = File.ReadAllLines(@"E:\test1.txt");
int i = 0;
string[] word;
for (int j=0;j<n;j++)// n is the no of items that the user want to fill the array with
{
word = (lines[j].Split(','));
word = (lines[j].Split(','));
Item[i].Weight = float.Parse(word[0]);// Item is the name of array
Item[i].Profit = float.Parse(word[1]);
i++;
}
Array.sort(Item,mycomparision);
}
所以我想计算这个方法的时间和空间复杂度(空间复杂度=输入大小+输出大小+任何数据结构)。我真的很困惑,数组的确切时间和空间复杂度是多少?结构和文本文件。当我计算空间复杂度或只是数组时,我认为文件大小是一个输入?我应该计算打开文件的时间并将数据作为时间复杂度读取到数组中吗?并且我的代码如此高效或者有更好更有效的代码(即如果文件包含100,000个项目,但用户只想读取100个项目,则可以先读取所有项目“string [] lines = File.ReadAllLines (@“E:\ test1.txt”);“然后只将100放到数组中”?请大家帮忙帮我^ _ ^。
答案 0 :(得分:-2)
The complexity of your program is O(n+2)
Since you have array of length n. you should need a max of n time units to find the element.
Then to get the two values of the struct you need another time units.
您不需要2n,因为对于数组的每个位置,您都有一个结构。
从我的分析一般来说,数组的时间复杂度是O(n)。您可以参考以下链接。
&安培;