Cover Image for Move all negative elements to one side of an Array uing C
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 array arr and its size n as parameters.
  • We initialize two pointers, left and right, at the start and end of the array, respectively.
  • We use a while loop to iterate until left is less than or equal to right.
  • Inside the loop, we have several cases:
  • If both arr[left] and arr[right] are negative, we move left pointer to the right.
  • If arr[left] is positive and arr[right] is negative, we swap the elements and move both pointers.
  • If both arr[left] and arr[right] are positive, we move right 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.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS