快速排序方法

参考《C++大学教程》第七版 19章课后题
</pre><pre name="code" class="cpp"><span style="font-size:18px;">// Exercise 19.10 Solution: Ex19_10.cpp
// Quick sort of a vector.
#include <iostream> 
#include <iomanip> 
#include <cstdlib>
#include <ctime>
#include <vector>
using namespace std;

// function prototypes
void quickSortHelper( vector < int > &, int, int );
int partition( vector < int > &, int, int );
void swap( int * const, int * const );

int main()
{
   const int MAX_NUMBER = 100;
   const int SIZE = 10;
   vector < int > vectorToBeSorted( SIZE );
   int loop;

   srand( time( 0 ) );

   // randomly generate content 
   for ( loop = 0; loop < SIZE; loop++ )
      vectorToBeSorted[ loop ] = rand() % MAX_NUMBER;

   cout << "Initial vector values are:\n";
   
   // print out values of the vector
   for ( loop = 0; loop < SIZE; loop++ )
       cout << setw( 4 ) << vectorToBeSorted[ loop ];

   cout << "\n\n";

   // if there is only one element
   if ( SIZE == 1 )
      cout << "Vector is sorted: " << vectorToBeSorted[ 0 ] << '\n';
   else 
   {
      quickSortHelper( vectorToBeSorted, 0, SIZE - 1 );
      cout << "The sorted vector values are:\n";

      for ( loop = 0; loop < SIZE; loop++ )
         cout << setw( 4 ) << vectorToBeSorted[ loop ];

      cout << endl;
   } // end else
} // end main

// recursive function to sort vector
void quickSortHelper( vector < int > &data, int first, int last )
{
   int currentLocation;

   if ( first >= last )
      return;

   currentLocation = partition( data, first, last ); // place an element
   quickSortHelper( data, first, currentLocation - 1 ); // sort left side
   quickSortHelper( data, currentLocation + 1, last ); // sort right side
} // end function quickSortHelper

// partition the vector into multiple sections
int partition( vector < int > &data, int left, int right )
{
   int position = left;

   // loop through the portion of the vector
   while ( true ) 
   {
      while ( data[ position ] <= data[ right ] && position != right )
         --right;

      if ( position == right )
         return position;

      if ( data[ position ] > data[ right ]) 
      {
         swap( &data[ position ], &data[ right ] );
         position = right;
      } // end if

      while ( data[ left ] <= data[ position ] && left != position )
         ++left;

      if ( position == left )
         return position;

      if ( data[ left ] > data[ position ] ) 
      {
         swap( &data[ position ], &data[ left ] );
         position = left;
      } // end if
   } // end while
} // end function partition

// swap locations
void swap( int * const ptr1, int * const ptr2 )
{
   int temp;

   temp = *ptr1;
   *ptr1 = *ptr2;
   *ptr2 = temp;
} // end function swap
</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值