Welcome

C Programming Tutorial


C Sorting Algorithms - Selection Sorting

Algorithm

  • Find the minimum element in an Array
  • Swap it with the value in the current position
  • repeat the above process for all element

Selection Sorting Complete C Program

#include <stdio.h>
int  findMin(int *a, int startPos,int endPos);
void display(int *a,int len);
void SWAP(int *p, int *q);
void selection_sort(int*a,int arrLen);
int main(){
        int a[]={3, 6, 1, 8, 4, 5};//{-2,11,10,-1,22,55,44,33};
        int arrLen = sizeof(a)/sizeof(a[0]);
        display(a,arrLen);
        selection_sort(a,arrLen);
        display(a,arrLen);
    return 0;
}

void selection_sort(int*a,int arrLen){
        for (int i=0; i < arrLen;i++){
                int minIndex = findMin(a,i,arrLen);
                SWAP(&a[minIndex],&a[i]);
        }

}
void SWAP(int *p, int *q){
    int t= *p;
    *p=*q;
    *q=t;


}

void display(int *a,int len){
    printf("\n %d,%d\n",sizeof(a),sizeof(a[0]));
for (int i=0; i < len;i++)
    printf("%d ",a[i]);
    printf("\n");
}

int  findMin(int *a, int startPos,int endPos){
    int min=a[startPos],minIndex=startPos;
    for(int i=startPos; i <endPos; i++){
        if(a[i]<min){
                min=a[i]; minIndex=i;
        }
    }
    return minIndex;
}

	

Time and Space Complexity

space: no Auxilary space required
Time: o(nsup2)

ADS