)RGB排序,一个字符串,里面只有三种字符R G B,所有的R都在G的前面,所有的G都在B的前面。将给定字符串按照此规律排序。要求不允许用辅助空间,复杂度控制在O(N)。遍历一遍就排好序。

#include "stdafx.h"
#include "stdlib.h"
#include 

#include 
#include 
#include 

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

你可能感兴趣的:(算法)