Problem Statement
You are required to write an iterative function which takes an integer array and arranges
its elements without using any extra array so that all the negative numbers precede all
the non-negative ones without disturbing the relative order among the negative ones
and similarly that among the non-negative ones. For example,
if the input array is 19 -23 17 2 -11 16 18 -4, then
the returned array is -23 -11 -4 19 17 16 18.
#include<stdio.h>
#include<stdlib.h>
void changeorder(int y[],int n);
int main()
{
int n,i,*y;
printf("enter the dimention of the array \n");
scanf("%d",&n);
printf("enter the entrys of array \n");
y=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
scanf("%d",&y[i]);
}
printf("before changing \n");
for(i=0;i<n;i++)
{
printf("%d ",y[i]);
}
printf("\n");
changeorder(y,i);
printf("after changing \n");
for(i=0;i<n;i++)
{
printf("%d ",y[i]);
}
return 0;
}
void changeorder(int y[],int n)
{
int i,temp,index;
i=1;
while(i<n)
{
while(y[i]>0 &&i<n)
{
i++;
}
index=i;
while(y[index-1]>0&& (index-1)>=0&& i<n)
{
temp=y[index-1];
y[index-1]=y[index];
y[index]=temp;
index--;
}
i++;
}
return ;
}
You are required to write an iterative function which takes an integer array and arranges
its elements without using any extra array so that all the negative numbers precede all
the non-negative ones without disturbing the relative order among the negative ones
and similarly that among the non-negative ones. For example,
if the input array is 19 -23 17 2 -11 16 18 -4, then
the returned array is -23 -11 -4 19 17 16 18.
#include<stdio.h>
#include<stdlib.h>
void changeorder(int y[],int n);
int main()
{
int n,i,*y;
printf("enter the dimention of the array \n");
scanf("%d",&n);
printf("enter the entrys of array \n");
y=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
scanf("%d",&y[i]);
}
printf("before changing \n");
for(i=0;i<n;i++)
{
printf("%d ",y[i]);
}
printf("\n");
changeorder(y,i);
printf("after changing \n");
for(i=0;i<n;i++)
{
printf("%d ",y[i]);
}
return 0;
}
void changeorder(int y[],int n)
{
int i,temp,index;
i=1;
while(i<n)
{
while(y[i]>0 &&i<n)
{
i++;
}
index=i;
while(y[index-1]>0&& (index-1)>=0&& i<n)
{
temp=y[index-1];
y[index-1]=y[index];
y[index]=temp;
index--;
}
i++;
}
return ;
}
No comments:
Post a Comment