#include "stdafx.h"
#include "stdlib.h"
#include <string>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
//算法中谈到了怎样不增加任何空间,交换两个元素的位置,在前面中介绍的是char型的加减法实现的,在做加减法实现的过程中要防止溢出,所以我这里换了个方法,使用异或实现!
void swap(std::string &StrSrc,int i,int j)
{
StrSrc[i]=StrSrc[i]^StrSrc[j];
StrSrc[j]=StrSrc[j]^StrSrc[i];
StrSrc[i]=StrSrc[i]^StrSrc[j];
return;
}
//返回flase表示排序已经完成
bool StringSortGG(std::string &StrSrc,int &i,int &j)
{
int ibegin,iend;
ibegin=i+1;
iend=j-1;
if (ibegin>iend)
{
return false; //
}
while (ibegin<=iend)
{
//
if (StrSrc[ibegin]=='R')
{
swap(StrSrc,i,ibegin);
i++;
break;
}else if (StrSrc[iend]=='B')
{
swap(StrSrc,j,iend);
j--;
break;
}else if (StrSrc[ibegin]=='B')
{
swap(StrSrc,ibegin,j);
j--;
break;
}else if (StrSrc[iend]=='R')
{
swap(StrSrc,i,iend);
i++;
}else{
ibegin++;
iend--;
if (ibegin>iend)
{
return false;
}
}
}
return true;
}
bool StringSort(std::string &StrSrc)
{
// std::string StrSrc="RGBBGRRBRGRBBG";
if (StrSrc.empty())
{
return false;
}
int i=0;
int j=StrSrc.length()-1;
while (i<j)
{
if (StrSrc[i]=='R')
{
i++;
}else if (StrSrc[j]=='B')
{
j--;
}else if (StrSrc[i]=='B')
{
swap(StrSrc,i,j);
j--;
}else if(StrSrc[j]=='R')
{
swap(StrSrc,i,j);
i++;
}else if ((StrSrc[i]=='G')&&(StrSrc[j]=='G'))
{
//
bool bRet=StringSortGG(StrSrc,i,j);
if (!bRet)
{
return true;
}
}
}
return true;
}
int main(void)
{
std::string StrSrc="RGBBGRRBRGRBBG";
StringSort(StrSrc);
}