# 將數組中的0和1分開

## 例

`arr[]={1,0,1,1,0,1,1,0}`
`0 0 0 1 1 1 1 1`

## 算法

```1. Traverse the array and get the count of total zero’s in the array.
2. Push ‘0’ that```

```.
3. Push ‘1’ (n – count) no of times in the array from the next position of 0 where we left inserting 0.
4. Print the array.```

## 履行

### 用於在數組中隔離0和1的C ++程序

```#include<iostream>

using namespace std;

void segregateZeroesOnes(int arr[], int n)
{
int count = 0;

for (int i = 0; i < n; i++)
{
if (arr[i] == 0)
count++;
}
for (int i = 0; i < count; i++)
arr[i] = 0;

for (int i = count; i < n; i++)
arr[i] = 1;
}

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

int main()
{
int arr[] = {1,0,1,1,0,1,1,0};
int n = sizeof(arr) / sizeof(arr[0]);

segregateZeroesOnes(arr, n);
printArray(arr, n);

return 0;
}
```
`0 0 0 1 1 1 1 1`

### 用於將數組中的0和1分離的Java程序

```class segregateZeroesOnes
{
public static void segregateZeroesOnes(int arr[], int n)
{
int count = 0;

for (int i = 0; i < n; i++)
{
if (arr[i] == 0)
count++;
}
for (int i = 0; i < count; i++)
arr[i] = 0;

for (int i = count; i < n; i++)
arr[i] = 1;
}

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[] args)
{
int arr[] = new int[] { 1,0,1,1,0,1,1,0 };
int n = arr.length;

segregateZeroesOnes(arr, n);
printArray(arr, n);

}
}
```
`0 0 0 1 1 1 1 1`

## 數組中分離0和1的複雜度分析

### 時間複雜度

O（N） 哪裡 “ n” 是數組中元素的數量。

### 空間複雜度

O（N） 哪裡 “ n” 是數組中元素的數量。