import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
int n= sc.nextInt();
int a[]= new int[n];
boolean isSorted=true;
for (int i=0;i<n;i++){
a[i]= sc.nextInt();
}
for (int i=1;i<=n-1;i++){
for(int j=0;j<n-1-i;j++){
if(a[j]>a[j+1]){
int temp = a[j];
a[j]= a[j+1];
a[j+1] = temp;
isSorted=false;
}}
if(isSorted)
break;
}
for(int e:a){
System.out.println(e);
}
}
}
Please tell me what is the problem with my code and suggest other changes so that I can clear all the test cases
Unable to clear all the test cases
@Vishu_1801 there is no use of is_sorted boolean variable
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
int n= sc.nextInt();
int a[]= new int[n];
boolean isSorted=true;
for (int i=0;i<n;i++){
a[i]= sc.nextInt();
}
for (int i=0;i<=n-1;i++){
for(int j=0;j<n-1-i;j++){
if(a[j]>a[j+1]){
int temp = a[j];
a[j]= a[j+1];
a[j+1] = temp;
}}
}
for(int e:a){
System.out.println(e);
}
}
}
It is optimization that if our array is sorted before n-1 times iteration we don’t need to proceed further iterations
Well how will that help me clear other test cases
@Vishu_1801
yeah that optimization will work for few testcases but you didn’t start you loop from i==0 thats was the main mistake
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
