Move all negative elements to end in c++
C++ program for Move all negative elements to end. Here more solutions.
// Include header file
#include <iostream>
using namespace std;
// C++ program for
// Move all negative elements at the end of array
class MyArray
{
public:
// Display array elements
void display(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
cout << " " << arr[i];
}
cout << endl;
}
// Swap the given array elements
void swap(int arr[], int start, int end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
// Method which is move negative elements
void moveNegative(int arr[], int n)
{
// first index
int i = 0;
// last index
int j = n - 1;
while (i < j)
{
if (arr[i] < 0 && arr[j] >= 0)
{
// When [i] index are have negative value
// And [j] is positive then swapping elements values
this->swap(arr, i, j);
// Modified index
i++;
j--;
}
else if (arr[i] >= 0)
{
// When element of [i] is not negative
i++;
}
else
{
j--;
}
}
}
};
int main()
{
MyArray *task = new MyArray();
// Array which are containing positive and negative values
int arr[] = {
1 , -1 , 3 , 2 , -7 , -5 , 11 , 6
};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Before Arrange : " << endl;
// Before move element
task->display(arr, n);
// Move negative elements
task->moveNegative(arr, n);
// After arrange
cout << "After Arrange : " << endl;
// After move element
task->display(arr, n);
return 0;
}
Output
Before Arrange :
1 -1 3 2 -7 -5 11 6
After Arrange :
1 6 3 2 11 -5 -7 -1
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment