【发布时间】:2021-07-19 02:05:54
【问题描述】:
我想分析复制函数调用次数的最佳和最坏情况。一般情况下会有什么难度?请帮我理解这个解决方案?
我认为最好的情况是 1,最坏的情况是 n-1,对吗?
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line size */
int get_line(char line[], int maxline);
void copy(char to[], char from[]);
/* print longest input line */
int main()
{
int es;
int len; /* current line length */
int max; /* maximum length seen so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* longest line saved here */
es=0;
max = 0;
while ((len = get_line(line, MAXLINE)) > 0)
if (len > max)
{
es++;
max = len;
copy(longest, line);
}
printf("%d",es);
if (max> 0) /* there was a line */
printf("\nlongest is:%s\n", longest);
return 0;
}
/* get_line: read a line into s, return length */
int get_line(char s[], int lim)
{
int c, i;
for (i=0; i<lim-1 && (c=getchar()) !=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n')
{
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
int i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
【问题讨论】:
标签: c algorithm time-complexity