+ 1
Why the sort can't actually sort
I try to code a code that sort but it can't actually sort, the output doesn't sort. Can someone explain? #include <stdio.h> int main() { int a,t; scanf("%d",&a); int b[a]; for(int i=0;i<=a;i++){ scanf("%d",&b[i]); } for(int I=a;I>=0;I--){ for(int j=0;j<=I;j++){ if(b[I]>b[I+1]){ t=b[I]; b[I]=b[I+1]; b[I+1]=t; } } } for(int l=0;l<=a;l++){ printf("%d",b[l]); } return 0; }
5 Answers
+ 2
for(int I=0;I<a;I++){
for(int j=0;j<a-1;j++){
if(b[j]>b[j+1]){
t=b[j];
b[j]=b[j+1];
b[j+1]=t;
}
}
//when size is a, indexes counts only 0 to a-1
Not include <=, only use <...
+ 3
You declared array size as equal to a, say ex:4
So array stores 0 to 3, (total of 4), if you greater than 3 index, you get garbage values, not sure which it will give...
So I said to take 0 to a-1,
But you are taking inputs 0 to a, so it will may not give same results every time...
In loop, use, j=0 to a-1, because,
When a[j] <a[j+1], j+1 value should not exceed array size,
If you try to access, you may get wrong results.. Or in java, or other languages it strictly give error..
é«äșé is it clears? Still any errors?
Is that total updated code, which you checking?
+ 1
Jayakrishna Thanks ïŒ
+ 1
Jayakrishna But why I insert 3321 when I using <a-1 the output is 1230 and when I using <=a-1 the output is 0123