0

Why isn't that code sorting an array?

#include <stdio.h> #include <stdlib.h> int main() { int x[5]={5,8,9,4}; int m=0; int n=1; int i =0; int h; for (m=0 ;m<5;m++){ for(n=1;n<5;n++){ if (x[m]>x[n]){ h=x[m]; x[m]=x[n]; x[n]=h; } } } printf("The numbers arranged in ascending order are given below \n"); for (i = 0; i < 5; i++) printf("%d\n",x[m]); }

21st Aug 2018, 1:43 AM
Retag Tarek
Retag Tarek - avatar
5 Respostas
+ 3
#include <stdio.h> #include <stdlib.h> int main() { int x[4]={5,8,9,4}; // edited int m=0; int n=1; int i =0; int length = sizeof(x)/sizeof(int); // edited int h; for (m=0 ;m<length-1;m++){ // edited for(n=m + 1;n<length;n++){ // edited if (x[m]>x[n]){ h=x[m]; x[m]=x[n]; x[n]=h; } } } printf("The numbers arranged in ascending order are given below \n"); for (i = 0; i < length; i++) // edited printf("%d\n",x[i]); // edited } I have modified/added 6, 11, 13, 14, 25, 26 lines.
21st Aug 2018, 1:54 AM
Steppenwolf
Steppenwolf - avatar
+ 3
Steppenwolf good edit. Just add 1 to n = m in the second for loop's init-statement to avoid redundant iteration over container. for (n = m+1; ...
21st Aug 2018, 7:26 AM
Babak
Babak - avatar
+ 2
Retag Tarek another version: #include <stdio.h> #include <stdlib.h> int main() { int x[5]={5,8,9,4}; int m=0; int n=1; int i =0; int h; for (m=0 ;m<5;m++){ for(n=0;n<4;n++){ if (x[n]>x[n+1]){ h=x[n]; x[n]=x[n+1]; x[n+1]=h; } } } printf("The numbers arranged in ascending order are given below \n"); for (i = 0; i < 5; i++) printf("%d\n",x[i]); } I have edited printf line with x[i ] and entire second for loop
21st Aug 2018, 2:02 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 2
C++ Soldier (Babak) the holy truth! Thank you! 🙂
21st Aug 2018, 11:15 AM
Steppenwolf
Steppenwolf - avatar
0
Time Complexity: O(n²) Space Complexity:O(1)
21st Aug 2018, 2:18 AM
Mohd Zaki
Mohd Zaki - avatar