Pages

Selection Sort

This method is a sorting method that will look for smallest or biggest value depend on ascending or descending order then being placed at the forefront place. After that, it will look for the next smallest or biggest value along all elements of array reduced by 1, and so on. For example, there is an array that contains these number :
31224135
If the data above is sorted in ascending by selection method, the result is:

Minimum ValueSorting Result
2
31224135
In 1st loop, it will look for smallest value between 1st and 6th element of array. 2 is the smallest value so its place will be switch with 1st element.
3
21234135
In 2st loop, it will look for smallest value between 2nd and 6th element of array. 3 is the smallest value so its place will be switch with 2nd element.
4
23124135
In 3rd loop, it will look for smallest value between 3rd and 6th element of array. 4 is the smallest value so its place will be switch with 3rd element.
5
23412135
In 4th loop, it will look for smallest value between 4th and 6th element of array. 5 is the smallest value so its place will be switch with 4th element.
12
23451312
In 5th loop, it will look for smallest value between 5th and 6th element of array. 12 is the smallest value so its place will be switch with 5th element.
Result
23451213


For implementation this sorting method, I use C program as an example.
First, I make a file that contains some numbers that will be sorted. I give its name "numberdata.txt". The numbers are separated by space. Second, I build a source code which is placed in the same folder with "numberdata.txt". I give its name "selectionsort.c" 
Here is the program in C. 

#include <stdio.h>
#include <stdlib.h>

const int ndata = 15;

int main()
{
    
//variables
    int array[ndata];
    int resultarray[ndata];
    int smallest;
    int smalpos;
  
  
 //read file "numberdata.txt"
    
//put the values which is got into an array
    FILE *pers;
    pers = fopen("numberdata.txt","r");
    int m;
    for(m=0; m<ndata; m++)
    {  
        fscanf(pers,"%d",&array[m]);
        printf("%d\t",array[m]);
    }
    fclose(pers);
    printf("\n");
  
    //put data in array into result array
    for(m=0; m<ndata; m++)
    {  
        resultarray[m] = array[m];
        printf("%d\t",resultarray[m]);
    }
    printf("\n");
  
    int n;
    
//sorting using selection sort
    for(m=0; m<ndata; m++)
    {
        smallest = resultarray[m];
        smalpos = m;
        for(n=m; n<ndata; n++)
        {
            if(resultarray[n]<smallest)
            {
                smallest = resultarray[n];
                smalpos = n;
            }
        }
        resultarray[smalpos] = resultarray[m];
        resultarray[m] = smallest;
    }
  
  
 //show result
    for(m=0; m<ndata; m++)
    {  
        printf("%d\t",resultarray[m]);
    }
    printf("\n");
  
    return 0;
}

You can download this work HERE.

1 comment: