Advertisement
thewitchking

Untitled

May 30th, 2025
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.90 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class BallSorter {
  4.     public static void main(String[] args) {
  5.         char[] balls = {'r', 'g', 'r', 'g', 'g', 'r'};
  6.  
  7.         int left = 0;
  8.         int right = balls.length - 1;
  9.  
  10.         while (left < right) {
  11.             // Move left pointer if it's already green
  12.             while (left < right && balls[left] == 'g') {
  13.                 left++;
  14.             }
  15.  
  16.             // Move right pointer if it's already red
  17.             while (left < right && balls[right] == 'r') {
  18.                 right--;
  19.             }
  20.  
  21.             // Swap if out of place
  22.             if (left < right) {
  23.                 char temp = balls[left];
  24.                 balls[left] = balls[right];
  25.                 balls[right] = temp;
  26.                 left++;
  27.                 right--;
  28.             }
  29.         }
  30.  
  31.         System.out.println("Sorted balls: " + Arrays.toString(balls));
  32.     }
  33. }
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement