In: Computer Science
Consider an array of length n containing positive and negative integers in random order. Write the C++ code that rearranges the integers so that the negative integers appear before the positive integers. write a program that includes both functions and a main() function that tests them. Name the two functions rearrangeN() and rearrangeN2().
PROGRAM :
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void print(int *arr, int size) {
for(int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << endl;
}
void swap_pos_neg(int *arr, int size) {
int left = 0, temp;
int right = size-1;
while(left < right) {
if(arr[left] < 0) {
left++;
continue;
}
if(arr[right] > 0) {
right--;
continue;
}
temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
int main() {
srand(time(NULL));
int size = 10;
int *arr = new int[size];
for(int i = 0; i < size; ++i) {
if(rand()%2 == 0) {
arr[i] = rand()%100;
} else {
arr[i] = -1*(rand()%100);
}
}
cout << "Initial array is ";
print(arr, size);
swap_pos_neg(arr, size);
cout << "Final array is ";
print(arr, size);
return 0;
}
Output :