[Updated] Goldman Sachs Aptitude Test Questions and Answers
Practice List of TCS Digital Coding Questions !!!
Take 50+ FREE!! Online Data Interpretation Mock test to crack any Exams.

Segregate/sort 0s and 1s in an array

Home > Programs > Sorting

87 / 6

Write a program to sort an array containing only 0's and 1's in random order.

Answer:

#include
#include 
using namespace std;
void segregate0and1(int arr[], int size)
{
    int left = 0, right = size-1;
    while (left < right)
    {
        while (arr[left] == 0 && left < right)
            left++;

        while (arr[right] == 1 && left < right)
            right--;
        if (left < right)
        {
            arr[left] = 0;
            arr[right] = 1;
            left++;
            right--;
        }
    }
}
int main()
{
    int arr[] = {0, 1, 0, 1, 1, 1};
    int i, arr_size = sizeof(arr)/sizeof(arr[0]);
    segregate0and1(arr, arr_size);
    cout

Asked In :: Aricent Paytm

Post Your Answer Here:

Language:

Post Your Reply Here:



Language:

Post Your Reply Here:



Language:

Post Your Reply Here: