C program to move negative elements to end in order with extra space allowed

In this blog post, we learn how to write a C program to move negative elements to end in order with extra space allowed? So if given an array of random numbers, push all the negative numbers of a given array to the end of the array. We will also see how to move negative elements to the end of the array using C programming.

Example,

Input : int arr[] = {1,-1,-3, -2, 7, 5, 11, 6 };


Output : 1 7 5 11 6 -1 -3 -2 

So let’s see the solution to the C program to move all negative elements at the end 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 end of the array.

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

#include <stdio.h>

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



// Moves all -ve element to end of array
void segregateElements(int arr[], int n)
{
    // Create an empty array to store result
    int temp[n];
    int j = 0; // track index of temp array
    int i = 0; // track index of the input array

    // Traversal array and store +ve element in
    // temp array
    for (i = 0; i < n ; i++)
    {
        if (arr[i] >= 0 )
        {
            //get +ve number
            temp[j++] = arr[i];
        }
    }

    //If given input array only contains
    // +ve and -ve number.
    if (j == n || j == 0)
    {
        return;
    }

    // Store -ve element in temp array
    for (i = 0 ; i < n ; i++)
    {
        if (arr[i] < 0)
        {
            temp[j++] = arr[i];
        }
    }

    // Copy contents of temp[] to arr[]
    memcpy(arr, temp, sizeof(temp));
}



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

    //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 negative elements to end in order with extra space allowed

One comment

Leave a Reply

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