The code didn’t pass test case 3. Can you tell me what’s the error and the what the correct code.
What's wrong in the code?
@rg361 When you have written this :
if(a[j] < a[i])
min = j;
instead of i you have to write min here bcoz you have to compare with min the indexed element.
if(a[j] < a[min])
min = j;
corrected code :
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
for(int i=0;i<n;i++)
a[i] = sc.nextInt();
int min = 0;
for(int i=0;i<n-1;i++)
{
min = i;
for(int j=i+1;j<n;j++)
{
if(a[j] < a[min])
min = j;
}
int temp = a[min];
a[min] = a[i];
a[i] = temp;
}
for(int i=0;i<n;i++)
System.out.println(a[i]);
}
}
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.