快速排序--递归实现

#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;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值