3,018 views
1 votes
1 votes

Consider an array consisting of –ve and +ve numbers. What would be the worst time comparisons an algorithm can take in order to segregate the numbers having same sign altogether i.e all +ve on one side and then all -ve on the other ?
(A) N-1

(B) N
(C) N+1
(D) (N*(N-1))/2

1 Answer

0 votes
0 votes

Take an example, given [1, 7, -5, 9, -12, 15]
The answer would be: [-5, -12, 1, 7, 9, 15]

Proceed with following steps :

  • Walk through the array and count negative numbers - O(n)
  • Create a new array of size O(n)
  • Walk through original array and place numbers into the new array. Use the known number of negative numbers to offset the positive ones - O(n)

Option B should be Correct.

                 or

a quick way to do it in Python. It slightly differs from the above in first creating an array for the negatives, then appending the positives. So it's not as efficient, but still O(n).

>>> a = [1,7,-5,9,-12,15]
>>> print [x for x in a if x < 0] + [y for y in a if y >= 0]
[-5, -12, 1, 7, 9, 15]

No related questions found