#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
const int SIZE = 10;
const int MAX_NUMBER = 1000;
void quicksort( int * const, int, int );
int partition( int * const, int, int );
void swap( int * const, int * const );
int main()
{
int arrayToBeSorted[ SIZE ] = {};
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;
}
}
void quicksort( int * const array, int first, int last )
{
int currentLocation;
if ( first >= last )
return;
currentLocation = partition( array, first, last ); // place an element
quicksort( array, first, currentLocation - 1 ); // sort left side
quicksort( array, currentLocation + 1, last ); // sort right side
}
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;
}
快速排序--递归实现
最新推荐文章于 2024-03-22 21:48:15 发布