Sunday, October 20, 2013

Array: Rearrange characters and intergers

Given an array[a1b2c3d4] -> convert to [abcd1234] with O(1) space and O(n) complexity.

3 comments:

  1. #include

    // A utility function to swap two elements
    void swap(char *a, char *b)
    {
    char temp = *a;
    *a = *b;
    *b = temp;
    }

    int isInteger(char c)
    {
    return c>='0' && c<='9';
    }

    void Arrangement(char arr[], int n)
    {
    int i,j;
    for(i=0;i<n/2;i++,j=i)
    {
    if(isInteger(arr[i]))
    {
    while(isInteger(arr[++j]))
    {
    swap(&arr[i],&arr[j]);
    }

    swap(&arr[i],&arr[j]);
    }

    }
    }
    // Driver program to test above functions
    int main()
    {
    char arr[] = "a1b2c3d4";
    int n = sizeof(arr)/sizeof(arr[0]);
    Arrangement(arr, n);
    printf("%s", arr);
    return 0;
    }

    ReplyDelete
  2. good one priyanka !!

    ReplyDelete