fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <cstring>
  4.  
  5. char *RGBorder(char *c_a, int num)
  6. {
  7. int middle = 0; // assume we only want the middle element
  8. int low = 0; // before the G's
  9. int high = num - 1; // after the G's
  10.  
  11. while (middle <= high)
  12. {
  13. if (c_a[middle] == 'R') // if we see an 'R' in the middle, it needs to go before the middle
  14. {
  15. std::swap(c_a[middle], c_a[low]); // swap it to a place before middle
  16. ++middle; // middle has creeped up one spot
  17. ++low; // so has the point where we will swap when we do this again
  18. }
  19. else
  20. if (c_a[middle] == 'B') // if we see a 'B' as the middle element, it needs to go after the middle
  21. {
  22. std::swap(c_a[middle], c_a[high]); // place it as far back as you can
  23. --high; // decrease the back position for next swap that comes here
  24. }
  25. else
  26. ++middle; // it is a 'G', do nothing
  27. }
  28. return c_a;
  29. }
  30.  
  31. int main()
  32. {
  33. char ca[] = "GBRRBRGGRRBG";
  34. std::cout << RGBorder(ca, strlen(ca));
  35. }
  36.  
Success #stdin #stdout 0s 4552KB
stdin
Standard input is empty
stdout
RRRRRGGGGBBB