I'm a new student in the field of coding. I'm trying to understand the concept of array. I wrote a code for sort an array. I will attach my code with this. Please describe what is the mistake on it.
#include<stdio.h>
void main(){
int a[5]={25,3,4,56,2};
int i,j,temp;
for(i=0;i<5-1;i ){
for(j=1;j<5;j ){
if(a[i]>a[j]){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(i=0;i<5;i ){
printf("%d ",a[i]);
}
}
The output: 2,25,56,3,4 in this order.
CodePudding user response:
The problem is with this line:
for(j=1;j<5;j ){
Change it to:
for(j=i 1;j<5;j ){
Otherwise it will swap previously sorted elements. The fixed version starts looking at the first element after the one being processed.