On Jun 26, 8:59 pm, sharad kumar <[email protected]> wrote:
> #include<iostream>
>
> using namespace std;
> int main()
> {
> int arry[5]={0,1,3,0,4};
> int i=0,j=0,k=0;
> for(;k<5;++k)
> {
> if((i==j)&&(arry[i]!=0))
> {
> ++i;
> ++j;
>
> }
>
> else if(i==j){
> j++;}
>
> else if(arry[j]==0){
> j++;}
>
> else if((arry[i] == 0) && (arry[j]!=0))
> {
> int tmp;
> tmp = arry[j];
> arry[j]=arry[i];
> arry[i]=tmp;
> i++;
> j++;
>
> }
> }
>
> for(i=0;i<5;++i)
> cout<<i;
> cin.sync();
> cin.get();
> return 0;
>
> }
>
> On Sun, Jun 27, 2010 at 1:57 AM, jalaj jaiswal
> <[email protected]>wrote:
> > Given an array of integers, {1,0,2,0,3,0,0,4,5,6,7,0,0,0}, you have to
> > create a new array which will be like (1,2,3,4,5,6,7,0,0,0,0,0,0,0}, without
> > using any other temporary array.
>
Wow. This seems too hard. I think we only have to copy the non-zero
elements forward and fill the rest of the array with 0's:
#include <stdio.h>
#define N_ELTS(A) (sizeof A / sizeof A[0])
int main(void)
{
int p, q, a[] = {1,0,2,0,3,0,0,4,5,6,7,0,0,0};
// Copy non-0's to front.
for (p = q = 0; p < N_ELTS(a); p++)
if (a[p] != 0)
a[q++] = a[p];
// Fill rest with zeros.
while (q < N_ELTS(a))
a[q++] = 0;
// Print results.
for (p = 0; p < N_ELTS(a); p++)
printf("%d ", a[p]);
printf("\n");
return 0;
}
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.