难得住寂寞的人才能笑到最后。。。

只要敲门才会有回音,才有可能走进去!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

快速排序!

Posted on 2008-11-28 21:12  xum  阅读(400)  评论(0)    收藏  举报

#include<iostream.h>

void isort( int a[], int left, int right );

void main()
{
 int i;
 int array[] = { 2, 5, 6, 10, 21, 3 };

 int len = sizeof( array )/sizeof( int );  // 求数组长度
 cout << "数组长度\n";
 cout << len << endl;

 cout << "原数组\n";
 for( i = 0; i < len; i++ ) // 输出原数组
 {
  cout << array[i] << "," ;
 }
 cout << endl << endl;

 isort( array, 0, len - 1 ); // 原函数调用
   
 cout << "排好的数组\n" ;
 for( i = 0; i < len; i++ )
 {
  cout << array[i] << "," ; 
 }
 cout << endl << endl;
}

void isort( int a[], int left, int right )
{
 int l, r, pivot, temp;
 l = left;                    // 0
 r = right;                  // len - 1
 pivot = a[ ( l + r )/2 ];  // 取中间
 while ( l < r )            // 将中间值的两边的数值对调
 {
  while ( a[l] < pivot ) //选取左边大于pivot 的值
   l++;
  while ( a[r] > pivot )  //选取右边大于pivot 的值
   r--;
  if( l >= r)            
   break;
  temp = a[l];  //交换位置
  a[l] = a[r];
  a[r] = temp;
  if( l != pivot )
  {
   --r;
  }
  if( r != pivot )
  {
   ++l;
  }
 }
 if( l == r )
  l++;
 if( left < r )
  isort( a, left, l - 1 );
 if( l < right )
  isort( a, r + 1, right );
}