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?
Algorithms – Fastest Algorithm for Dividing Array into Positive and Negative Numbers
algorithmsarraysorting
Best Answer
That task is simple:
Iterate from start and end at the same time, and swap the element if needed.
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.