# 將所有負元素移動到最後，並留出額外的空間

## 問題陳述

“將所有負元素按順序移動，並在末尾留有多餘的空間”指出，您將獲得一個同時包含正數和負數的數組。 問題語句要求將所有否定元素移到數組的最後。

## 例

`arr[] = { 1,2,-3,-5,2,7,-9,-11 }`
`1, 2, 2, 7, -3, -5, -9, -11`

## 將所有負元素按順序移到最後的算法，並留出額外的空間

```1. Declare an array same as the size of the original array.
2. Traverse the array and check if any number is greater than or equal to 0,
1. If true then copy that number from the 0th position of the array we created.
3. Now traverse the array and check if any of the numbers is less than 0.
1. If true, then copy that value to the array we created from the next position where the positive number ends.
4. Now copy that temporary array we created into the original array and print that array.```

## 推薦碼

### C ++代碼將所有否定元素按順序移到末尾，並留有多餘的空間

```#include<bits/stdc++.h>
using namespace std;

void segregateElements(int arr[], int n)
{
int temp[n];

int j = 0;

for (int i = 0; i < n ; i++)
if (arr[i] >= 0 )
temp[j++] = arr[i];

if (j == n || j == 0)
return;

for (int i = 0 ; i < n ; i++)
if (arr[i] < 0)
temp[j++] = arr[i];

memcpy(arr, temp, sizeof(temp));
}

void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}

int main()
{
int arr[] = { 1,2,-3,-5,2,7,-9,-11 };
int n = sizeof(arr)/sizeof(arr[0]);

segregateElements(arr, n);
printArray(arr,n);

return 0;
}
```
`1 2 2 7 -3 -5 -9 -11`

### Java代碼將所有否定元素按順序移動到末尾，並留有額外的空間

```import java.util.Arrays;

class moveNegativeElement
{
public static void segregateElements(int arr[], int n)
{
int temp[] = new int[n];

int j = 0;

for (int i = 0; i < n; i++)
if (arr[i] >= 0)
temp[j++] = arr[i];

if (j == n || j == 0)
return;

for (int i = 0; i < n; i++)
if (arr[i] < 0)
temp[j++] = arr[i];

for (int i = 0; i < n; i++)
arr[i] = temp[i];
}
public static void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
public static void main(String arg[])
{
int arr[] = { 1,2,-3,-5,2,7,-9,-11 };
int n = arr.length;

segregateElements(arr, n);
printArray(arr,n);

}
}
```
`1 2 2 7 -3 -5 -9 -11`