Advertisement
rishu110067

Untitled

Feb 9th, 2022 (edited)
822
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.60 KB | None | 0 0
  1. # Using Insertion sort
  2. # Time Complexity : O(n^2)
  3. # Auxiliary Space: O(1)
  4.  
  5. def online_median(stream):
  6.  
  7.     results = []
  8.     for i in range(len(stream)):
  9.         # stream[0..j-1] is already sorted
  10.         # insert stream[j] at the correct position in order to keep stream[0...j] sorted
  11.         j = i
  12.         while j > 0 and stream[j] > stream[j-1]:
  13.             stream[j], stream[j-1] = stream[j-1], stream[j]
  14.             j = j-1
  15.        
  16.         if i % 2 == 0:
  17.             results.append(stream[i//2])
  18.         else:
  19.             results.append((stream[i//2] + stream[i//2 + 1]) // 2)
  20.     return results
  21.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement