sidhique kerala
sidhique kerala

Reputation: 47

what is the mistake in this simple sorting array code?

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.

Upvotes: 0

Views: 60

Answers (1)

Tom Karzes
Tom Karzes

Reputation: 24052

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.

Upvotes: 1

Related Questions