......................

Selection Sort

Posted by Unknown On Thursday, July 22, 2010 0 comments

/***************************************
------------------------------
SELECTION SORT ALGORTHM
------------------------------
Selection.Sort(num,n,least)
1. for i from 1 to n, Repeat step 2 & 3
2. find Least item of the array and,
  save index to least
3. Swap Least Element with ith Element
4. Return
****************************************/

#include "iostream.h"
#include "conio.h"

void swap(int &a,int &b)
{
int temp = a;
a = b;
b = temp;
}

int main()
{
int num[50],i,j,n,least;
cout << "How many numbers? ";
cin >> n;
cout << "\nEnter " << n << " Numbers\n";
for(i = 0;i < n ;i++)
  cin >> num[i];

for(i = 0;i < n;i++)
  {
   least = i; //set least to first index
   for(j = i + 1;j < n;j++) //from next index to n
    if(num[j] < num[least]) //find least element
     least = j; //Save Index

   swap(num[least],num[i]); //Swap least element with ith element
  }

//Print Output
cout << endl;
for(i = 0;i < n;i++)
  cout << num[i] << ' ';

getch();
return 0;
}

OUTPUT

How many numbers? 10

Enter 10 Numbers
25 65 47 88 64 10 -98 0 35 6

-98 0 6 10 25 35 47 64 65 88

Download Original File

Selection.cpp

No comments:

Post a Comment

Leave Feedback about this BLOG