Featured Post

Trie implementation in C

Selection Sort Implementation in C

Selection Sort algorithm works in three steps:

1. Find the minimum value in the list.
2. Swap it with the value in the first position.
3. Repeat the steps above for the remainder of the list (starting at the second position and
advancing each time)

Here's a simple implementation of Selection Sort in C

#include<stdio.h>

void display(int *arr , int start, int end);

void swap(int *a , int *b) 
{
    *a = *a - *b; 
    *b = *b + *a; 
    *a = *b - *a; 
}

int findmin(int arr[], int start, int end)
{
    int min = arr[start];
    int ret = start;
    for(; start < end ; start++)
    {   
        if(arr[start] < min)
        {   
            min = arr[start];
            ret = start;
        }   
    }   

    return ret;         // Returns the index of the minimum value in the range
}

void selection_sort(int *arr, int nmem)
{
    int start = 0;
    int end = nmem;
    int minIndex;

    for(; start < end; start++)
    {
        minIndex = findmin(arr,start,end);     //Find minimum value in the array

        if(arr[start] != arr[minIndex])        //If the minimum value lies at start
            swap(&arr[start],&arr[minIndex]);

    }

}

void display(int arr[] , int start , int end)
{
    int i;
    for(i = start; i < end ; i++)
        printf("%d ",arr[i]);
    printf("\n");
}

int main()
{
    int arr[] = {12,2,54,23,57,21,78,34};

    int nmem = sizeof(arr)/sizeof(int);

    display(arr,0,nmem);
    selection_sort(arr,nmem);
    display(arr,0,nmem);
}

Comments

  1. Selection Sort in C

    Selection sort is simplest way to sort array elements. Selection sort is based of maximum and minimum value. First check minimum value in array list and place it at first position (position 0) of array, next find second smallest element in array list and place this value at second position (position 1) and so on. Same process is repeated until sort all element of an array.

    ReplyDelete

Post a Comment

Please post your valuable suggestions