Friday, 14 October 2011

Source code for Selection Sort


/********************************************************\
 * ***************                       ************** *
 * *             *    SELECTION SORT     *            * *
 * ***************                       ************** *
/********************************************************/


#include <iostream.h>
#include <conio.h>
#include <malloc.h>


void selection_sort(int a[],int n); //Prototype of the calling function..


void main()
{
  int i,n;
  int* a;
  clrscr();
  cout << "Enter the no of elements: ";
  cin  >> n;
  a = (int*) malloc(sizeof(int)*n);
  cout << "\nEnter the  elements:\n\n";
  for(i = 0; i < n; i++)
  {
    cin >> a[i];
  }
  selection_sort(a,n);
  cout << "\nSorted array is:\n\n";
  for(i = 0; i < n; i++)
  {
    cout << "\t" << a[i] << "\n" ;
  }
  getch();
}


void selection_sort(int a[],int n)
{
  int i,j,temp,loc,min;
  for(i = 0; i < n; i++)
  {
    min = a[i];
    loc = i;
    for(j = i+1; j < n; j++)
    {
      if(a[j] < min)
      {
      min = a[j];
loc = j;
      }
    }
    if(loc != i)
    {
      temp = a[i];
      a[i] = a[loc];
      a[loc] = temp;
    }
  }
}


Output :

No comments:

Post a Comment