I have written a C code for insertion sort. However, I am facing issue when I try to execute the j loop in the below code. The code is not able to execute the if statement and print the text 'test'.
//inner loop for comparison
for(j=i-1;j>=0;j--){
if(temp<a[j]){
printf("test");
a[j+1]=a[j];
// printf("%d\t",a[j]);
}
a[j+1]=temp;
}
However, when I change the code and add temp<a[i]
in the j loop like this for(j=i-1;j>=0 && temp<a[i];j--)
and commented if statement, it worked and 'test' statement got successfully printed. Below is the code that works fine:
//inner loop for comparison
for(j=i-1;j>=0 && temp<a[j];j--){
//if(temp<a[j]){
printf("test");
a[j+1]=a[j];
// printf("%d\t",a[j]);
// }
a[j+1]=temp;
}
My question is why in the first code it was not able to execute if statement and print the text while in the second modified code it worked. If temp<a[i]
was false in the first if statement code, it should be false in the second case as well when I moved it to the for loop. I am confused why the results differ in the both cases?
Aucun commentaire:
Enregistrer un commentaire