• Selection Sort

    Selection Sort

    Introduction:

    In selection sort the list is divided into two sub-lists sorted and unsorted. These two lists are divided by imaginary wall. We find a smallest element from unsorted sub-list and swap it to the beginning. And the wall moves one element ahead, as the sorted list is increases and unsorted list is decreases.

    Assume that we have a list on n elements. By applying selection sort, the first element is compared with all remaining (n-1) elements. The smallest element is placed at the first location. Again, the second element is compared with remaining (n-1) elements. At the time of comparison the smaller element is swapped with larger element. Similarly, entire array is checked for smallest element and then swapping is done accordingly. Here we need n-1 passes or iterations to completely rearrange the data.

    Algorithm of Selection Sort:

    Selection_sort (array, size)Where array -> Represents the list of elements

    Size -> Represents size of the list

    Step 1: current = 0 [initially]

    Step 2: Repeat through Step 7 while (current < size)

    Step 3: j = current + 1;

    Step 4: Repeat through Step 6 while (j < size)

    Step 5: if  (array [current] > array [j])

    (i)                               temp = array[current]

    (ii)                             arra[current] = array[j]

    (iii)                            array[j] =temp

    step 6: j = j + 1

    Step 7: current = current + 1

    Step 8: Exit

    Example of Selection Sort on Array/List using C Language

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

    void selection_sort[int array[], int size)

    {

    int temp, current, j;

    for(current = 0; current < size; current++)

    for(j = current +1; j < size; j++)

    if(array[current] > array[j])

    {

    temp = array[current];

    array[current] = array[j];

    array[j] = temp;

    }

    }

    void main()

    {

    int values[30], i;

    printf(“\n Unsorted list is as follows\n”)

    for(i = 0; i < 30; i++)

    {

    values[i] = rand() % 100;

    printf(“%d”, values[i]);

    }

    selection_sort(values, 30 );

    printf(“\n sorted list is as follows\n”);

    for ( i = 0; i < 30; i++)

    printf(“%d”, values[i]);

    }

    Appreciate my work :Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPin on PinterestShare on RedditShare on StumbleUponShare on TumblrDigg thisShare on YummlyShare on VKFlattr the authorBuffer this page

Leave a Reply

Your email address will not be published. Required fields are marked *