Advertisement
yujason007

CS381 HW2

Jan 23rd, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. 3)
  2. i) Assume index of arrays is from 1 to n.
  3.  
  4. Create an array, B of size n, initialized to 0;
  5. FOR i = 1 to n
  6. IF B[A[i]] is nonzero
  7. RETURN (B[A[i]], i)
  8. ELSE
  9. SET B[A[i]] to i
  10. END IF
  11. END FOR
  12.  
  13. Algorithm is O(n) because there is only 1 for loop of size n and the work being done inside the loop is constant time. The worst case happens when we find the pair at the last index
  14.  
  15.  
  16. ii) Assume index of arrays is from 1 to n.
  17.  
  18. Create an array, B of size n, initialized to 0;
  19. FOR i = 1 to n:
  20. increment B[A[i]];
  21. END FOR
  22. SET sum = 0
  23. FOR i = 1 to n:
  24. IF B[i] > 1
  25. increment sum by B[i]*(B[i]-1)/2
  26. END IF
  27. END FOR
  28. RETURN sum
  29.  
  30. Algorithm is O(n) because there are two separate loops of size n and within both of these loops, constant time work is done.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement