468 views
0 votes
0 votes
Consider an array of length n consisting only of positive and negative integers.Design an algorithm to rearrange the array so that all the negative integers appear before all the positive integers,using O(n) time and only constant amount of extra space.

2 Answers

1 votes
1 votes

int i, j = 1
for j = 1 to Arr.length
      key = Arr[j]
      if Arr[j] < 0
          Arr[j] = Arr[i]
          Arr[i] = key
          i++
edited by
0 votes
0 votes
Maintain two indexes to traverse.Initialize first index left as 0 and second index right as n-1.

Do following while left<right:

1. keep inc index left while there are -ve no at it

2. keep dec index right while there are +ve no at it

3. if left<right then exchange A[left] and A[right]

Void Rearrange(int A[], int n)

{

      int left=0,right=n-1;

     while(let<right)

        {

             if(A[left]<0 && left<right)

                left++;

           elseif(A[right]>0 && left<right)

              right--;

          else

              {

                    if(left<right)

                         {

                         int temp;

                         temp=A[left];

                         A[left]=A[right];

                        A[right]=temp;

                         left++;

                        right--;

               }

          }

    }

}

Time Complexity=O(n)

Space Complexity=O(1)

Note:Please take help from Algorithm book by Narasimha Karumanchi

Related questions

2 votes
2 votes
3 answers
3
Anurag_s asked Aug 15, 2015
2,707 views
Consider 2 scenarios:C1: For DFA (ϕ, Ʃ, δ, qo, F),if F = ϕ, then L = Ʃ*C2: For NFA (ϕ, Ʃ, δ, qo, F),if F = ϕ, then L = Ʃ*Where F = Final states setϕ = Total st...
0 votes
0 votes
1 answer
4
N asked May 1, 2019
522 views
Consider a max-heap of n distinct integers, n ≥ 4, stored in an array A[1 . . . n]. The second minimum of A is the integer that is less than all integers in A except th...