工大后院

 找回密码
 加入后院

扫一扫,访问微社区

QQ登录

只需一步,快速开始

搜索
查看: 1206|回复: 1

分析程序

[复制链接]
发表于 2007-12-2 23:46 | 显示全部楼层 |阅读模式
请大哥大姐们帮忙分析一下程序中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;
}
发表于 2007-12-3 16:37 | 显示全部楼层
找本说排序的书自已看看吧
给点耐心就能看明白了
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 加入后院

本版积分规则

QQ|Archiver|手机版|小黑屋|广告业务Q|工大后院 ( 粤ICP备10013660号 )

GMT+8, 2025-5-15 02:00

Powered by Discuz! X3.5

Copyright © 2001-2024 Tencent Cloud.

快速回复 返回顶部 返回列表