Home > front end >  Why is this code for Selection Sort Algorithm not giving output?
Why is this code for Selection Sort Algorithm not giving output?

Time:12-10

The code:

#include <stdio.h>

int main() {
    int i, j, temp, a[10] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }, n = 10;

    printf("Before sorting, the array is:");
    for (i = 0; i < n; i  )
        printf("%d ", a[i]);

    for (i = 0; i < n - 1; i  ) {
        temp = i;
        for (j = i   1; j < n; j  ) {
            if (a[j] < a[temp])
                temp = j;
        }
        if (temp != i) {//for swapping
            a[j] = a[j]   a[temp];
            a[temp] = a[j] - a[temp];
            a[j] = a[j] - a[temp];
        }
    }
    printf("\nAfter sorting, the array is:");
    for (i = 0; i < n; i  )
        printf("%d ", a[i]);

    return 0;
}

The Output:

enter image description here

The sorted values are not being printed. Where are the errors in this code?

CodePudding user response:

The output the code you've listed produces is:

Before sorting, the array is:9 8 7 6 5 4 3 2 1 0 
After sorting, the array is:9 8 7 6 5 4 3 2 0 4198464 

link:

https://godbolt.org/z/o3nfz9Yv3

The garbage at the end appears to be a result of this code:

        if(temp!=i)
        {//for swapping
            a[j]=a[j] a[temp];
            a[temp]=a[j]-a[temp];
            a[j]=a[j]-a[temp];
        }

When this code executes, j is always equal to n, which means you are always accessing invalid data on a[j]. I think you meant to use 'i' inplace of 'j'.

CodePudding user response:

The output does not appear because you do not print a newline after the numbers. Some systems require this for proper output.

Note however that the swapping code is incorrect: you should swap a[temp] and a[i], not a[j].

Swapping values by adding and subtracting is incorrect: it does not work for floating point values and non numerical types and has undefined behavior for signed integers in case of overflow. You should use a temporary variable:

#include <stdio.h>

int main() {
    int i, j, temp;
    int a[10] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
    int n = sizeof(a) / sizeof(a[0]);

    printf("Before sorting, the array is:");
    for (i = 0; i < n; i  ) {
        printf(" %d", a[i]);
    }
    printf("\n");

    for (i = 0; i < n - 1; i  ) {
        temp = i;
        for (j = i   1; j < n; j  ) {
            if (a[j] < a[temp])
                temp = j;
        }
        if (temp != i) {//for swapping
            int t = a[temp];
            a[temp] = a[i];
            a[i] = t;
        }
    }
    printf("After sorting, the array is:");
    for (i = 0; i < n; i  ) {
        printf(" %d", a[i]);
    }
    printf("\n");

    return 0;
}
  • Related