小弟不才,自己写了个快速排序算法,如下:
#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次划分操作。但确实能处理各种情况,还待日后完善。