Algorithms – Fastest Algorithm for Dividing Array into Positive and Negative Numbers

algorithmsarraysorting

Given array of integers I am trying to design the fastest algorithm that swaps the elements such that at the end : all negative elements are on the left and then the positive elements, for example, final output might me [-5,-1,-3,10,11,2], Of course, direct sorting with n*lgn gives the desired answer but I am looking for faster algorithm if possible, any suggestions?

Best Answer

That task is simple:

Iterate from start and end at the same time, and swap the element if needed.

A = index_first
B = index_last
while A < B
    while A < B and v[A] < 0
        A++
    while A < B and not v[B] < 0
        B--
    if A < B
        swap(v[A], v[B])

You get N comparisons (once for each element) and at most N/2 swaps (if the elements were all at the wrong end, and half should be at the front/end), which is the bare minimum.