Implement the selection sort algorithm for int-arrays. : Sort « Data Structure « C++






Implement the selection sort algorithm for int-arrays.

Implement the selection sort algorithm for int-arrays.
#include <iostream>
#include <iomanip>
#include <cstdlib>        
#include <ctime>          
using namespace std;

void selectionSort( int array[], int length);
const int length = 200;
int intArray[length];
int main()
{
   srand( (unsigned int)time(NULL));
   for( int n=0; n < length; ++n)
       intArray[n] = (rand() % 20000)-10000;

   selectionSort( intArray, length);

   cout << "The sorted numbers:" << endl;
   for( int i = 0; i < length; ++i)
      cout << setw(8) << intArray[i];
   cout << endl;
   return 0;
}

void selectionSort( int *array, int length)
{
   register int *p, *mp;   
   int *last = array + length-1;  
   for( ; array < last;  ++array)
   {
      mp = array;                     
      for( p = array+1; p <= last; ++p) 
         if( *mp > *p)
             mp = p;
      swap( *array, *mp);
   }
}
inline void swap( int& a, int& b)
{
   int temp = a;  
   a = b;  
   b = temp;
}

           
       








Related examples in the same category