Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading