Web Toolbar by Wibiya

Pages

Thursday, January 26, 2012

Given an array of 0s and 1s, segregate 0s on left and 1s on right side.

Solution #1: Here is the code,

void segregate01(int* arr, int len)
{
    int start = 0;
    int end = len-1;

    while(start < end)
    {
        while((arr[start] == 0) && (start != end))
            start++;

        while((arr[end] == 1) && (end != start))
            end--;

        if(start < end)
        {
            swap(&(arr[start]), &(arr[end]));
        }
    }
}

No comments: