in DS
331 views
1 vote
1 vote
#include <stdio.h>

void SSort(int [], int);

void swap(int *,int*);

int main() {

    int arr[] = {5,4,3,2,1,0};

    int n = sizeof(arr)/sizeof(arr[0]);

    SSort(arr,n);

    for(int i = 0; i < n; i++) {

        printf("%d\t", arr[i]);

    }

    return 0;

}

void SSort(int a[], int n) {

    int t, i, j;

    for(i = 1; i <= n-1; i++) {

        t = a[i-1];

        for(j = i; j <= n-1; j++) {

            if(t > a[j])

                t = a[j];

        }

        swap(&t, &a[i-1]);

    }

}

void swap(int *x, int *y) {

    int tmp = *x;

    *x = *y;

    *y = tmp;

}

 

This is a selection sort algorithm. But the output of the algo is: 0 0 0 0 0 0. Where is the problem ?
in DS
331 views

1 Answer

1 vote
1 vote
Best answer
swap(&t,&a[i-1]);

in this line you are swapping only the value stored in the variable t but not swaping the actual array’s element.