# 将数组中的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” 是数组中元素的数量。