Sunday, October 6, 2013

Q. Position all elements less than 0 before elements greater than 0

INPUT                     6, -1, -2, 2, -4, 3, 5
OUTPUT                 -4, -2,-1  2 ,6 ,3 ,5



This  is  a  very  common  question  asked  in  which  can  be  of  form  arranging  all  even  numbers  before than  odd  ones  or  keeping  all  0  values  before  1 etc....  And  they  always  expect  you  to  solve  in  one  scan  and  in  place...


METHOD 1

In  this  we  take  another  array  of  same  size  and  first  push  all  the  negative  elements  and  then  in  second  scan  er  push  all  positive  elements..

Time  Complexity= O(n)
Space COmplexity=O(n)

METHOD 2

We  take  two  pointers  ptr1  and  ptr2.

ptr1  points  to  first  occurence  of  positive  elements,,

and  ptr2  searches  the  negative  number  to  the  right  of  ptr1  if  we  do  not  find  any  -ve  number  we  break...

else  we  we  swap  them  and  find  our  new  ptr1  which  is  obviously  greater  than  the  previous  value


#include<stdio.h>
void swap(int*,int,int);
void swap(int *arr,int ptr1,int ptr2)
{
int temp=arr[ptr1];
arr[ptr1]=arr[ptr2];
arr[ptr2]=temp; }

int main()
{
int bbreak=true;
int arr[7]={6, -1, -2, 2, -4, 3, 5};
int ptr1=-1,ptr2=-1;
//ptr1 maintains  the  first  +ve  element
while(1)
{
for(int k=ptr1;k<7;k++)
if(arr[k]>0)
{ptr1=k;break;}
for(int k=ptr1;k<7;k++)
{
if(arr[k]<0)
{swap(arr,ptr1,k);bbreak=false;}
}
if(bbreak==true)
break;
bbreak=true;
}
for(int k=0;k<7;k++)
printf("%d\t",arr[k]);
}

No comments:

Post a Comment