How to sort all elements in an array such that all negative numbers are first, and then positive numbers.

    int ar[] = {-2,3,4,-5,6,9,-1,-5};
    int i = 0;
    int j = sizeof(ar) / sizeof(ar[0]) - 1;
    while(i <= j)
        while(ar[i] < 0) { i++; }
        while(ar[j] >= 0) { j--; }

        if (i < j) {
            std::swap(ar[i], ar[j]);

So this code is pretty simple. First we are creating an array of numbers, some negative, some positive, not in any order. Second we determine two index values, one at the beginning of the array and one at the end of the array. Then, as long as the starting index is less than or equal to the ending index, we loop.

After this we basically find the two indices to swap. We do two while loops. While the element in ar[i] is less than 0, which means it’s negative, increase i by 1. We stop once ar[i] is not negative. Then we do another loop where ar[j] is greater than or equal to zero, which means it is positive, and we keep doing this until a number that is not positive is found.

Finally, we just swap the values once we have found one that is positive and one that is negative. The final if statement if (i < j) is to make sure that we don’t swap it incorrectly after i is incremented by 1.

This is just a simple leetcode style question I found the solution to so I wanted to share it. The time complexity should be O(N).

Leave a Reply

Your email address will not be published. Required fields are marked *