Topic : Selection Sort
Author : Ilia Yordanov
Page : 1

#include <iostream.h>

//Selection Sort function
//Takes two parameters:
//int *array- the array with the numbers to be sorted
//int size- the size of the array
void selsort(int *array,int size)
{
 int min;
 int b;
 
 //This loop goes through the whole array
 for(int a=0;a<size-1;a++)
 {
  b=a;
  min=array[b]; //Get the current value

  //...and check if any of the rest numbers is lower
  for(int j=a+1;j<size;j++)
  {
   if(array[j]<min)
   {
    b=j; min=array[b]; //...and if yes, then get it
   }
  }

  //Switch the values...
  array[b]=array[a];
  array[a]=min;

 }
}

//Main program function
void main()
{
beginning:
 const int maxsize=100;
 int count;
 char answer;

 cout << "How many numbers you want to sort?: ";
 cin>> count;
 if(count>maxsize)
 {
  cout<<"Too many..."<<endl;
  cout<<"Your limit is: "<<maxsize<<endl;
  cout<<"Want to try again? (y/n): ";
  cin>>answer;
  if(answer=='y')
   goto beginning;
  else
   cout<<endl<<"Bye bye...!"<<endl;
 }
 else
 {
  int *numbers;
  numbers=new int[count];

  for(int y=0;y<count;y++)
  {
   cout<<"Enter number #"<<y+1<<" : ";
   cin>>numbers[y];
  }
  
  selsort(numbers,count); //Sort the numbers...

  cout<<endl<<endl;

  //Print the results...
  cout<<"Result: "<<endl;
   for(int h=0;h<count;h++)
   cout << numbers[h]<<" ";

  cout<<endl;

  //Free the memory...
  delete [] numbers;
 }
}



Page : 1