This is an ascending order sorting problem from descending order | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

This is an ascending order sorting problem from descending order

#include <stdio.h> int main() { int n,i; printf("Enter the size of the array : "); scanf("%d",&n); int arr[n]; printf("enter the elements in the array : "); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } for(i=0;i<n;i++) { printf("the elements entered at index %d: %d\n",i,arr[i]); } int temp=0; printf("the sorted array is : "); for(i=0;i<n;i++) { if(arr[i]>arr[i+1]){ temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } } for(i=0;i<n;i++){ printf("%d",arr[i]); } return 0; } Input: 10 9 8 7 6 5 Expected output : 5 6 7 8 9 10 Original output : 9 8 7 6 5 01 Whats the wrong here ? Why it's only changing the first element why not the whole thing?

3rd Apr 2021, 5:38 PM
kreddyt
kreddyt - avatar
3 Answers
+ 2
because it checks every number against every other number. one loop only checks numbers next to eachother. write the values out on a peice of paper if that helps you see it better
3rd Apr 2021, 6:10 PM
Slick
Slick - avatar
+ 1
i only see one for loop in there to bubble sort them. i beleive it uses 2. int i, x; for (i=0; i<(n-1); i++) for (x=1; x<n; x++) if (arr[i] > arr[x]) { // sort here }
3rd Apr 2021, 5:58 PM
Slick
Slick - avatar
0
Yeah can u explain why we've used 2 loops
3rd Apr 2021, 6:06 PM
kreddyt
kreddyt - avatar