Hi,
Coping my code below for reference. However link to code is posted on question also.
/* package codechef; // don’t place package name! */
import java.util.;
import java.lang.;
import java.io.*;
/* Name of the class has to be “Main” only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int intTestCase = Integer.parseInt(str);
for(int i = 0 ; i < intTestCase;i++ ){
String lengthOfStr = br.readLine();
boolean value = false;
String intputString = br.readLine();
StringBuilder buff = new StringBuilder(intputString);
int reverse = 0;
for(int j = intputString.length() - 1 ; j >= 2; j=j-2){
int tmp1 = intputString.charAt(j) - 48;
int tmp2 = intputString.charAt(j-2) - 48;
if(tmp1 > tmp2){
buff.setCharAt(j,(char) (tmp2 + 48));
buff.setCharAt(j-2,(char) (tmp1 + 48));
value = true;
reverse = j;
break;
}
}
if(value){
int minValue = 0;
int indexToSwap = -1;
for(int k=reverse;k <= intputString.length() - 2;k+=2){
minValue = buff.charAt(k) - 48;
for(int h = k +2; h <= intputString.length() - 1; h+=2){
int tmp1 = buff.charAt(h) - 48;
if(minValue > tmp1){
minValue = tmp1;
indexToSwap=h;
}
}
if(indexToSwap != -1){
buff.setCharAt(indexToSwap,(char) (buff.charAt(k)));
buff.setCharAt(k, (char) (minValue+48));
}
indexToSwap = -1;
}
}
if(value){
String result = new String(buff);
System.out.println(result.replaceAll(" “,”"));
}
else{
System.out.println("-1");
}
}
}
}