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; }
Recommended Articles for you:
- Best gift for programmers.
- Best electronic kits for programmers.
- C program to find the Median of two sorted arrays of different sizes.
- C Program to find first and last position of element in sorted array
- Write C program to find the missing number in a given integer array of 1 to n
- C program to find the most popular element in an array
- Find the largest and smallest element in an array using C programming.
- C program to find even occurring elements in an array of limited range
- Find sum of all sub-array of a given array.
- C program to segregate even and odd numbers
- Find an element in array such that sum of left array is equal to sum of right array.
- C Program to find the count of even and odd elements in the array.
- Write C program to find the sum of array elements.
- C program to find odd occurring elements in an array of limited range
- Find the sum of array elements using recursion
- C Program to reverse the elements of an array
- C Program to find the maximum and minimum element in the array
- Calculate size of an array in without using sizeof in C
- How to create a dynamic array in C?
- How to access 2d array in C?
- Dangling, Void, Null and Wild Pointers