C program to move all negative numbers to beginning and positive to end with constant extra space

In this blog post, we learn how to write a C program to move all negative numbers to the beginning and positive to end with constant extra space? So if an array of random numbers, push all the negative and positive numbers to the beginning and end of the array. We will also see how to segregating the negative and positive numbers of a given array.

Example,

Input: -12, 11, -13, -5, 6, -7, 5, -3, -6 

Output: -12 -13 -5 -7 -3 -6 11 6 5

So let’s see the solution to the C program to move all negative elements at the beginning of the array without changing the order of positive elements and negative elements. Suppose arr is a given integer array of size N (arr[N] ), the task is to write the C program to move all negative elements to the beginning of the array.

If you want to learn more about the C language, you can check this course, Free Trial Available.

C program to move all negative numbers to the beginning and positive to end with constant extra space

#include <stdio.h>

//Calculate array size
#define ARRAY_SIZE(a)  sizeof(a)/sizeof(a[0])


//swap function not handle null pointer scenario
//not much safe to use
void swap(int *s1, int *s2)
{
    int temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}

// Moves all -ve element to begining of array
void segregateElements(int arr[], int n)
{
    int i =0,j = 0;

    for (i = 0; i < n; i++)
    {
        if (arr[i] < 0)//non-zero
        {
            if (i != j)
            {
                swap(&arr[i],&arr[j]);
            }
            j++;
        }
    }
}


int main()
{
    int arr[] = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };

    //get array size
    int arr_size = ARRAY_SIZE(arr);

    int i = 0;

    segregateElements(arr, arr_size);

    for (i = 0; i < arr_size; i++)
    {
        printf("%d ",arr[i]);
    }

    return 0;
}

C program to move all negative numbers to beginning and positive to end with constant extra space

Leave a Reply

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