
165 views
Move all negative elements to one side of an Array uing C
To move all negative elements to one side of an array in C, you can use a two-pointer approach. Here’s an example program that demonstrates this:
C
#include <stdio.h>
void moveNegatives(int arr[], int n) {
int left = 0;
int right = n - 1;
while (left <= right) {
if (arr[left] < 0 && arr[right] < 0) {
left++;
} else if (arr[left] > 0 && arr[right] < 0) {
// Swap arr[left] and arr[right]
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
} else if (arr[left] > 0 && arr[right] > 0) {
right--;
} else {
left++;
right--;
}
}
}
int main() {
int arr[] = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original Array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
moveNegatives(arr, n);
printf("Array after moving negatives to one side: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
In this program:
moveNegatives
is a function that takes an arrayarr
and its sizen
as parameters.- We initialize two pointers,
left
andright
, at the start and end of the array, respectively. - We use a while loop to iterate until
left
is less than or equal toright
. - Inside the loop, we have several cases:
- If both
arr[left]
andarr[right]
are negative, we moveleft
pointer to the right. - If
arr[left]
is positive andarr[right]
is negative, we swap the elements and move both pointers. - If both
arr[left]
andarr[right]
are positive, we moveright
pointer to the left. - Otherwise, we move both pointers.
- After the loop, the negative elements will be on the left side and the positive elements on the right side.
In the main
function, we demonstrate this by initializing an array with both positive and negative numbers, calling moveNegatives
, and then printing the modified array.