|
请大哥大姐们帮忙分析一下程序中void quicksort( int * const, int, int );函数的定义.谢谢!
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::setw;
#include <cstdlib>
using std::rand;
using std::srand;
#include <ctime>
using std::time;
const int SIZE = 10;
const int MAX_NUMBER = 1000;
void quicksort( int * const, int, int );
void swap( int * const, int * const );
int main()
{
int arrayToBeSorted[ SIZE ] = { 0 };
int loop;
srand( time( 0 ) );
for ( loop = 0; loop < SIZE; loop++ )
arrayToBeSorted[ loop ] = rand() % MAX_NUMBER;
cout << "Initial array values are:\n";
for ( loop = 0; loop < SIZE; loop++ )
cout << setw( 4 ) << arrayToBeSorted[ loop ];
cout << "\n\n";
if ( SIZE == 1 )
cout << "Array is sorted: " << arrayToBeSorted[ 0 ] << '\n';
else
{
quicksort( arrayToBeSorted, 0, SIZE - 1 );
cout << "The sorted array values are:\n";
for ( loop = 0; loop < SIZE; loop++ )
cout << setw( 4 ) << arrayToBeSorted[ loop ];
cout << endl;
}
return 0;
}
void quicksort( int * const array, int first, int last )
{
int partition( int * const, int, int );
int currentLocation;
if ( first >= last )
return;
currentLocation = partition( array, first, last );
quicksort( array, first, currentLocation - 1 );
quicksort( array, currentLocation + 1, last );
}
int partition( int * const array, int left, int right )
{
int position = left;
while ( true )
{
while ( array[ position ] <= array[ right ] && position != right )
right--;
if ( position == right )
return position;
if ( array[ position ] > array[ right ])
{
swap( &array[ position ], &array[ right ] );
position = right;
}
while ( array[ left ] <= array[ position ] && left != position )
left++;
if ( position == left )
return position;
if ( array[ left ] > array[ position ] )
{
swap( &array[ position ], &array[ left ] );
position = left;
}
}
}
void swap( int * const ptr1, int * const ptr2 )
{
int temp;
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
} |
|