给定一个随机顺序为0和1的数组。分隔数组左侧的0和右侧的1。遍历数组仅一次。
例子:
Input : arr[] = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0]
Output : arr[] = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
Input : arr[] = [1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1]
Output : arr[] = [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1]
我们已经讨论过将数组中的0和1分离的解决方案
在这篇文章中,讨论了一个新的解决方案。
第1步:在这里,我们可以使用两个指针,即从开头(索引= 0)开始的type0(对于元素0)和从结束索引开始的type1(对于元素1)。
步骤2:我们打算将1放置在数组的右侧。一旦我们完成了此操作,那么0肯定会朝向数组的左侧以实现此目标,我们接下来将进行以下操作。
我们比较索引类型为0的元素
1)如果为1,则应将其移到右侧,因此一旦交换,我们需要将其与索引type1交换,我们确保索引type1的元素为’1’,因此我们需要减少索引type1
2)否则它将为0,那么我们需要简单的递增索引type0
C++14
// CPP program to sort an array with two types
// of values in one traversal.
#include
using namespace std;
/* Method for segregation 0 and 1 given
input array */
void segregate0and1(int arr[], int n)
{
int type0 = 0;
int type1 = n - 1;
while (type0 < type1) {
if (arr[type0] == 1) {
swap(arr[type0], arr[type1]);
type1--;
}
else {
type0++;
}
}
}
// Driver program
int main()
{
int arr[] = { 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1 };
int n = sizeof(arr)/sizeof(arr[0]);
segregate0and1(arr, n);
for (int a : arr)
cout << a << " ";
}
Java
// Java program to sort an array with two types
// of values in one traversal.public class GFG {
/* Method for segregation 0 and 1
given input array */
class segregation {
static void segregate0and1(int arr[], int n)
{
int type0 = 0;
int type1 = n - 1;
while (type0 < type1) {
if (arr[type0] == 1) {
// swap type0 and type1
arr[type0] = arr[type0] + arr[type1];
arr[type1] = arr[type0] - arr[type1];
arr[type0] = arr[type0] - arr[type1];
type1--;
}
else {
type0++;
}
}
}
// Driver program
public static void main(String[] args)
{
int arr[]
= { 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0 };
segregate0and1(arr, arr.length);
for (int a : arr)
System.out.print(a + " ");
}
}
Python3
# Python3 program to sort an array with
# two types of values in one traversal.
# Method for segregation 0 and
# 1 given input array
def segregate0and1(arr, n):
type0 = 0; type1 = n - 1
while (type0 < type1):
if (arr[type0] == 1):
arr[type0], arr[type1] = arr[type1], arr[type0]
type1 -= 1
else:
type0 += 1
# Driver Code
arr = [1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1]
n = len(arr)
segregate0and1(arr, n)
for i in range(0, n):
print(arr[i], end = " ")
# This code is contributed by Smitha Dinesh Semwal
C#
// C# program to sort an array with two types
// of values in one traversal.
using System;
class GFG {
static void segregate0and1(int []arr, int n)
{
int type0 = 0;
int type1 = n - 1;
while (type0 < type1)
{
if (arr[type0] == 1)
{
// swap type0 and type1
arr[type0] = arr[type0] + arr[type1];
arr[type1] = arr[type0]-arr[type1];
arr[type0] = arr[type0]-arr[type1];
type1--;
}
else {
type0++;
}
}
}
// Driver program
public static void Main()
{
int []arr = { 1, 1, 1, 0, 1, 0, 0,
1, 1, 1, 1 };
segregate0and1(arr, arr.Length);
for (int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by vt_m.
PHP
Javascript
输出:
0 0 0 1 1 1 1 1 1 1 1
时间复杂度: O(n)
辅助空间: O(1)