数据结构作业-如何求时间复杂度

1.For each of the following six program fragments:Give an analysis of the running time(Big-Oh will do)

(1) sum = 0;
        for (i=0;i<N;i++)
           sum++;

答:O( N

(2) sum = 0;
        for (i=0;i<N;i++)
            for(j=0;j<N;j++)
                sum++;

答:O( N2

(3) sum = 0;
        for (i=0;i<N;i++)
            for(j=0;j<N*N;j++)
                sum++;

答:O( N3

(4) sum = 0;
        for (i=0;i<N;i++)
            for(j=0;j<i;j++)
                sum++;

答:O( N2

(5) sum = 0;
        for (i=0;i<N;i++)
            for(j=0;j<i*i;j++)
                for(k=0;k<j;k++)
                sum++;

答:O( N5

(6) sum = 0;
        for (i=0;i<N;i++)
            for(j=0;j<i*i;j++)
                if(j%i == 0)
                  for(k=0;k<j;k++)
                       sum++;

答:O( N4

2.Description: Given a group of N numbers, determine the kth largest, where N > k .
Solution 1:
(1) read N numbers into an array,
(2) sort the array in decreasing order by some simple algorithm (such as bubblesort),
(3) return the element in position k.
Solution 2:
(1) read the first k elements into an array and sort them in decreasing order,
(2) each remaining element is read one by one,
(2.1) If it is smaller than the kth element in the array, it is ignored;
(2.2) Otherwise, it is placed in its correct spot in the array, bumping one element out of the array.
(3) the element in the kth position is returned as the answer
Which solution is better when
(1) N ~ k
(2) N » k ?

答:在(1)的情况下,Solution 1和Solution 2都行;
在(2)的情况下,Solution 2要比Solution 1好;
但是当N很大很大时(比如百万、千万级),Solution 1和Solution 2都要花很长时间去运行才能给出结果;
综上所述,Solution 2是对Solution 1的改进,但还远远不够,二者都不算较优结果。

你可能感兴趣的:(数据结构)