C++/Data Structure/Sort

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Implement the selection sort algorithm for int-arrays.

<source lang="cpp">

  1. include <iostream>
  2. include <iomanip>
  3. include <cstdlib>
  4. 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;

}

      </source>