0

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.

1
  • This is not a sorting algorithm. Tracks what happen by printing swapped values and array content at each iteration, you'll understands. Commented May 18, 2022 at 9:40

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively, maybe do for(j=i;j<5-1;j++) if(a[j] > a[j+1]). Mostly a matter of style I guess.
@Lundin Either works. I figure doing an integer addition (by one) is cheaper than doing 2 array loads (of the same value) and a compare, although the addition does add an instruction to the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.