Jul 21, 2014

C Programming Challenge #03: Sort - selection

Following article will discuss about sorting technique called as selection sort. Sorting is a activity of arranging elements in order. Order can be increasing or decreasing. As the name suggests in each iteration of the loop, element is selected for a position. By the end of the loop whole array would be sorted. 


It can be depicted as in below figure



Strategy:
  • Lets have the number in array name 'a'.
    • Sorting will be done by function sort_select that has following prototype
    • int sort_select(int *arr, int max);
    • arr is pointer to array where the data is there.
    • max is the length of the array.
  • Lets have a function print_array that will help us print the content of the array.
    • Which has following prototype
    • void print_array(int *arr, int max);
  • Lets have a function swap which will be used to swap the numbers
    • void swap(int *p, int *q)
Selection sort program will be as follows


#include <stdio.h>

#define NUM_ELE(a) sizeof(a)/sizeof(a[0])

int sort_select(int *, int);
void print_array(int *, int);
void swap(int *, int *);
int main()
{
   int a[] = {4, 5, 1, 2};

   printf("Unsorted Array is - ");
   print_array(a, NUM_ELE(a));
   printf("\n");

   sort_select(a, NUM_ELE(a));
   printf("Sorted Array is - ");
   print_array(a, NUM_ELE(a));
   printf("\n");
}
int sort_select(int *arr, int max)
{
   int i, j;
   int min_place;
   /* Loop to go though whole array */
   for(i = 0; i < max; i++) {
      /* Starting from i till end
         of array find place of minimum  */
      min_place = i;
      for(j = i; j < max; j++) {
         if(arr[j] < arr[min_place]) 
            min_place = j;
         }
      }
      swap(arr[i], arr[min_place]);
   }
   return 0;
}
void print_array(int *arr, int n)
{
   int i;
   for(i = 0; i < n; i++) {
      printf(" %d", arr[i]);
   }
}

void swap(int *p, int *q) 
{
   int temp;
   temp = *p;
   *p = *q;
   *q = temp;
   return;
} 


Output will look as follows -


Unsorted Array is -  4 5 1 2
Sorted Array is -  1 2 4 5

Links

Next Article - C Programming Challenge #04: Sorting - merge
Previous Article - C Programming Challenge #02: Sort - insertion
All Article - C Programming Challenge

No comments :

Post a Comment