+ 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; }

10th Mar 2020, 8:42 AM
高于鈞
高于鈞 - avatar
5 ответов
+ 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 <...
10th Mar 2020, 8:55 AM
Jayakrishna 🇮🇳
+ 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?
10th Mar 2020, 6:40 PM
Jayakrishna 🇮🇳
10th Mar 2020, 8:43 AM
高于鈞
高于鈞 - avatar
+ 1
Jayakrishna Thanks !
10th Mar 2020, 6:22 PM
高于鈞
高于鈞 - avatar
+ 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
10th Mar 2020, 6:28 PM
高于鈞
高于鈞 - avatar