How to rearrange positive and negative numbers in array in c++ language
ADVERTISEMENTS
How to rearrange positive and negative numbers in array in c++ language. In this program, you will learn how to rearrange positive and negative numbers using the loops & functions.
Take an example to rearrange the elements through a c++ program:
// How to rearrange positive and negative
// numbers in array in c++ language
#include <bits/stdc++.h>
using namespace std;
void alterNumber(int *arru, int i, int j) {
int temp = arru[i];
arru[i] = arru[j];
arru[j] = temp;
}
void splitNegativeElement(int *arru, int size) {
int temp, left = 0, right = size - 1;
while (right > left) {
while (arru[left] < 0)
left++;
while (arru[right] > 0)
right--;
if (left < right) {
alterNumber(arru, left, right);
}
}
}
// It's the driver function of
// array element arrangements
void reArrangeNumbers(int *arru, int size) {
int i, j;
splitNegativeElement(arru, size);
for (i = 0; arru[i] < 0; i++);
for (j = 1; (j < i) && (arru[j] < 0); j += 2) {
alterNumber(arru, i, j);
i++;
}
return;
}
int main() {
int i, arru[] = { -24, 28, -25, -26, 25, 39, 37, 31, -31, -31, 39 };
int arru_size = sizeof(arru) / sizeof(arru[0]);
// It's the array iteration
cout << "------This is the given array before arrangement------\n\t";
for (i = 0; i < arru_size; i++) {
cout << arru[i] << ",\t";
}
cout << "\n\n";
// It's the array iteration
cout << "------This is the Re-arranged array------\n\t";
// This will re-arrange the given array
reArrangeNumbers(arru, 10);
for (i = 0; i < 11; i++) {
cout << arru[i] << ",\t";
}
cout << "\n";
return 0;
}
Output
------This is the given array before arrangement------
-24, 28, -25, -26, 25, 39, 37, 31, -31, -31, 39,
------This is the Re-arranged array------
-24, 39, -25, 37, -31, 31, -26, 25, -31, 28, 39,