快速排序算法源码

小弟不才,自己写了个快速排序算法,如下:

#include <iostream>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

bool QuickSort( int *array, int from, int to )
{
    if( (to - from) < 1)
         return true;
   else
   {
      int pivot = array[from];
      int front = from + 1;
      int rear = to;
      int moveArea = from;
      bool rorf = false;
      while( front <= rear )
      {
          if( rorf == false)
          {
               if( array[rear] <= pivot )
               {
                    array[moveArea] = array[rear];
                    moveArea = rear;
                    rear--;
                    rorf = true;
               }
         else rear--;
      }

     else
     {
         if( array[front] >= pivot )
         {
             array[moveArea] = array[front];
             moveArea = front;
             front++;
             rorf = false;
         }
         else front++;
     }
  }
  array[moveArea] = pivot;
  QuickSort( array, from, moveArea - 1 );
  QuickSort( array, moveArea + 1, to );
 }
}

int main()
{
     int data[] = {49, 38, 65, 97, 76, 13, 27, 67, 99, 100, 50, 43, 122, 21, 40, 56, 300, 400, 1, 35, 22, 90, 100, 299, 678};
     int size = sizeof(data) / sizeof(int);
     int from = 0;
     int to = size - 1;
     QuickSort( data, 0, size );
     for( int i=0; i < size; i++ )

         
cout << data[i] <<" ";
     cout << endl;
     return 1;
}
 

该算法是一个递归算法,pivot的选择是直接选择划分中的第一个元素。这样有可能在一个划分还剩下3个元素的时候扔需要进行3次划分操作。但确实能处理各种情况,还待日后完善。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值