Wednesday, November 27, 2013

Selection sort

 
Example. Sort {5, 1, 12, -5, 16, 2, 12, 14} using selection sort.




Selection sort example


lets make it C language


#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
 int arr[] = {5, 1, 12, -5, 16, 2, 12, 14};
 int i=0;
 int j=0;
 int count=0;
 int min=0;
 int temp;

 count = sizeof(arr)/sizeof(arr[0]);


 for(i;i<count-1; i++){
  min =i;
  for(j=i+1;j<count; j++){
   if(arr[min]>arr[j]){
    min=j;
   }
  }
  temp = arr[i];
  arr[i] = arr[min];
  arr[min] = temp;
 }
 i=0;
 for(i=0; i<count; i++){
  printf("%d ", arr[i]);
 }
 return 0;
}

No comments:

Post a Comment