...

/

Solution Review : Rearrange Positive & Negative Values

Solution Review : Rearrange Positive & Negative Values

This review provides a detailed analysis of the different ways to solve the "Rearrange Positive & Negative Values" challenge.

Solution #1: Using new array #

Press + to interact
namespace chapter_2
{
class Solution
{
//Re-Arrange Positive and Negative Values of Given Array
static void reArrange(int []arr, int size)
{
int[] newArray = new int[size];
int newArray_index = 0;
//Fill newArray with negative values first.
//Then fill it with positive values.
//In the end, insert every element of newArray back into the original array, arr.
for (int i = 0; i < size; i++)
{
if (arr[i] < 0)
newArray[newArray_index++] = arr[i];
}
for (int i = 0; i < size; i++)
{
if (arr[i] >= 0)
newArray[newArray_index++] = arr[i];
}
for (int j = 0; j < newArray_index; j++)
{
arr[j] = newArray[j];
}
// delete[] newArray;
}
static void Main(string[] args)
{
int size = 6;
int []arr = { 2, 4, -6, 0, -5, -10 };
Console.Write("Array before rearranging: ");
for (int i = 0; i < size; i++)
Console.Write(arr[i] + " ");
Console.WriteLine("");
reArrange(arr, size);
Console.Write("Array after rearranging: ");
for (int i = 0; i < size; i++)
Console.Write( arr[i] + " ");
Console.WriteLine("");
}
}
}

In this solution, iterate over the entire given array, and copy all negative numbers to a newly ...