Search code examples
csortingswapfunction-definitionselection-sort

I'm a beginner and practising C selection sort but getting different output for different values


I have below code for performing selection sort:

#include<stdio.h>
    int main(){
       //selection_sort(int,int);
       int a[] = {55,932,53,98};
       int n = sizeof(a)/sizeof(a[0]);
    //    printf("%d \n",n);
       
       printf("Array before sorting: ");
       for (int i = 0; i < n; i++){
           printf("%d ", a[i]);
       }
       selection_sort(a,n);
       printf("Array after sorting: ");
       for (int k = 0; k < n; k++){
           printf("%d ", a[k]);
       }
    }
    int selection_sort(int a[], int n){
        int i,j,minidx,tmp;
        //int a[size];
        for (i = 0; i < n - 1 ; i++){
            minidx = i;
            for (j = i + 1; j < n; j++){
                if (a[minidx] > a[j]){
                        minidx = j;
                        swap_elements(&a[minidx], &a[i]);
                }
            }
        }
    }
    int swap_elements(int *a, int *b){
        int tmp = *a;
        *a = *b;
        *b = tmp;
    }

I have tried different values for the array and it is randomizing the accuracy. What am I doing I'm not supposed to do?


Solution

  • Your algorithm for selection sort is correct apart from the call to swap elements. The elements should be swapped once the minimum element has been found.

    #include<stdio.h>
    int swap_elements(int *a, int *b){
        int tmp = *a;
        *a = *b;
        *b = tmp;
    }
    int selection_sort(int a[], int n){
        int i, j, minidx;
        for (i = 0; i < n - 1 ; i++){
            minidx = i;
            for (j = i + 1; j < n; j++){
                if (a[minidx] > a[j]){
                    minidx = j;
                }
            }
            swap_elements(&a[minidx], &a[i]);
        }
    }
    
    int main(){
       int a[] = {64, 25, 12, 22, 11};
       int n = sizeof(a) / sizeof(a[0]);
       
       printf("Array before sorting: ");
       for (int i = 0; i < n; i++){
           printf("%d ", a[i]);
       }
       selection_sort(a, n);
       printf("Array after sorting: ");
       for (int k = 0; k < n; k++){
           printf("%d ", a[k]);
       }
    }
    

    Try this code instead.