原文地址:
http://www.cnblogs.com/gnuhpc/archive/2012/12/21/2828166.html
http://blog.csdn.net/v_july_v/article/details/6211155
/*
* =====================================================================================
*
* Filename: Dutchflag.cpp
*
* Description:
*
* Version: 1.0
* Created: 02/25/2011 09:31:21 AM
* Revision: none
* Compiler: gcc
*
* Author: gnuhpc , warmbupt@gmail.com
*
* =====================================================================================
*/
#include <iostream>
#include <stdlib.h>
using namespace std;
#define N 10
void swap (int &var1, int &var2)
{
int temp = var1;
var1 = var2;
var2 = temp;
}
void shuffle(int *array)
{
int current = 0;
int end = N-1;
int begin = 0;
while( current<=end )
{
if( array[current] ==0 )
{
swap(array[current],array[begin]);
current++;
begin++;
}
else if( array[current] == 1 )
{
current++;
}
else{//When array[current] =2
swap(array[current],array[end]);
end--;
}
}
}
int main(int argc, char *argv[])
{
int a[N];
int i;
for( i=0 ; i<N; i++ )
{
a[i] = rand()%3;
cout << a[i] << " ";
}
cout << endl;
shuffle(a);
for( int i=0 ; i<N ; i++ )
{
cout << a[i] << " ";
}
cout << endl;
return 0;
}