problem link is :http://www.codechef.com/problems/JOHNY/
why following code is not giving output???
#include<stdio.h>
#include<stdlib.h>
void swap(long int *,long int );
main()
{
int t,j,pos,i,n,c;
long int a,temp;
scanf("%d",&t);
for(j=0;j<t;j++)
{
scanf("%d",&n);
a=(long int)malloc(nsizeof(long int));
for(i=0;i<n;i++)
scanf("%ld",&a[i]);
scanf("%d\n",&pos);
temp=a[pos-1];
while(1)
{
c=0;
for(i=0;i<n;i++)
{
if(a[i+1]<a[i])
{
swap(&a[i+1],&a[i]);
c++;
}
}
if(c==0)
break;
}
for(i=0;i<n;i++)
{
if(a[i]==temp)
printf("%d\n",i);
}
}
}
void swap(long int *a,long int *b)
{
long int t;
t=*a;
*a=*b;
*b=t;
}
Please help me in correcting the code…
Since I couldn’t read the code in question, referred this solution of yours from submissions page.
Here is a part of your code.
for(i=0;i<n;i++)
{
if(a[i+1]<a[i])
{
swap(&a[i+1],&a[i]);
c++;
}
}
In the above code, i
value varies from 0 to n-1. When suppose i = 1
, it enters the for loop and accesses a[i+1] i.e. a[n]
which could be any garbage value. You can access only from a[0] to a[n-1] for array of size n.
Change your for loop statement to
for(i = 0; i < n-1; i++)
please post it…by adding a new line after every statement…its difficult to read code like this…