0

Let's say there is an array A of size n. Which has some elements in it. Target is to print them as fast as possible. The printed order does not matter.

The naive algorithm will be,

print_number (A)
    for(i = 0 to n)
        print A[i]

And it will have time complexity of O(n)

And what about the below one ?

print_number (A, l, r)
if (l == r)   // terminating condition
    print A[i]
else
    mid = (l+r)/2
    print_number (A, l, mid)
    print_number (A, mid, r)

This will be O(n)

[EDITED] What if we use parallelism, assume enough processors.

print_number (A, l, r)
if (l == r)   // terminating condition
    print A[i]
else
    mid = (l+r)/2
    spawn print_number (A, l, mid) // assign to a new thread / processor
    print_number (A, mid, r)

Will it be O(lgn) ? or O(n) ?

prime
  • 14,464
  • 14
  • 99
  • 131
  • If the output contains n things then there's n print statements executed. – Paul Hankin Aug 13 '16 at 13:51
  • Ahh missed one critical point in the question. One recursive call has to be spawned. – prime Aug 13 '16 at 14:03
  • What does `print` do in your model of computation? I'd expect it serializes its inputs into a stream and therefore the program will still be O(n), no matter how much parallelism you have in the parallel part. It's https://en.wikipedia.org/wiki/Amdahl%27s_law in action. – Paul Hankin Aug 14 '16 at 02:57
  • @PaulHankin `print` will just print an element of the array. – prime Aug 15 '16 at 07:58

0 Answers0