Selection Sort - C Program

#include<stdio.h>
/* Logic : For every index from 0 to number_of_elements-1, we find the element which is appropriate
           for that index and we swap the element which is already there with the element which is supposed to
           be in that position. Finding the element which is appropriate for an index is simple. We only need to
           find the minimum value which is present between that index and the last element
( the last element is at index = number_of_elements-1, given that we are using a zero-based array).
 */

void SelectionSort(int *array,int number_of_elements)
{
       
int iter,jter,minIndex,temp;
       
for(iter = 0;iter<number_of_elements;iter++)
       
{
               
/*minIndex denotes the index which has the minimum value which for now assumed to be
                 the vlaue at current index and we update it in the for loop given below
                 */

                minIndex
= iter;
               
for(jter = iter+1; jter<number_of_elements;jter++)
               
{
                       
if(array[jter] < array[minIndex])
                       
{
                               
/* If some index has got element smaller than minimum then update
                                   minindex  to be that index*/

                                minIndex
= jter;
                       
}
               
}
                temp
= array[iter];
                array
[iter] = array[minIndex];
                array
[minIndex] = temp;
       
}
}
int main()
{
       
int number_of_elements;
        scanf
("%d",&number_of_elements);
       
int array[number_of_elements];
       
int iter;
       
for(iter = 0;iter < number_of_elements;iter++)
       
{
                scanf
("%d",&array[iter]);
       
}
       
/* Calling this functions sorts the array */
       
SelectionSort(array,number_of_elements);
       
for(iter = 0;iter < number_of_elements;iter++)
       
{
                printf
("%d ",array[iter]);
       
}
        printf
("\n");
       
return 0;

}
Comments