this is my code for https://www.spoj.com/problems/JNEXT/
import java.util.;
class tery {
void ans(int a[])
{
int l=a.length,count=0;
int i=l-1,j=i-1,x,k=11,i1=0,j1=0,cc=0;
while(count<l-1)
{
if(a[i]>a[j])
{
x=j+1;
while(x<l)
{
if(a[x]>a[j])
{
if((a[x]-a[j])<k)
{
k=a[x]-a[j];
i1=j;
j1=x;
}
}
++x;
cc=1;
}
}
if(cc==1)break;
–i;–j;++count;
}
int pp=a[i1];
a[i1]=a[j1];
a[j1]=pp;
if((i1+1)<(l-1))
{
int rr[]=Arrays.copyOfRange(a,i1+1,a.length);
Arrays.sort(rr);
int e=-1;
/ for(int t=i1+1;t<l;++t){
a[t]=rr[++e];
}*/
for(int r=0;r<l;++r)
{
if(r>i1)System.out.print(rr[++e]+" “);
else System.out.print(a[r]+” “);
}
}
else
{
for(int r=0;r<l;++r)
{
System.out.print(a[r]+” ");
}
}
System.out.println();
}
}
public class MyClass
{
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
int c=sc.nextInt();
while(c>0)
{
int l=sc.nextInt();
int[] aa=new int[l];
for(int i=0;i<l;++i)
{
aa[i]=sc.nextInt();
}
tery r1=new tery();
r1.ans(aa);
–c;
}
}}
it is showing time limit exceeded