Advertisement
Guest User

Untitled

a guest
Dec 19th, 2014
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Random;
  3.  
  4. public class DutchNationalFlag {
  5. enum DutchColors {
  6. RED, WHITE, BLUE
  7. }
  8.  
  9. public static void main(String[] args) {
  10. DutchColors[] balls = new DutchColors[12];
  11.  
  12. DutchColors[] values = DutchColors.values();
  13. Random rand = new Random();
  14. for (int i = 0; i < balls.length; i++)
  15. balls[i] = values[rand.nextInt(values.length)];
  16.  
  17. System.out.println("Before: " + Arrays.toString(balls));
  18.  
  19. dutchNationalFlagSort(balls);
  20.  
  21. System.out.println("After : " + Arrays.toString(balls));
  22. }
  23.  
  24. private static void dutchNationalFlagSort(DutchColors[] items) {
  25. int lo = 0, mid = 0, hi = items.length - 1;
  26.  
  27. while (mid <= hi)
  28. switch (items[mid]) {
  29. case RED:
  30. swap(items, lo++, mid++);
  31. break;
  32. case WHITE:
  33. mid++;
  34. break;
  35. case BLUE:
  36. swap(items, mid, hi--);
  37. break;
  38. }
  39. }
  40.  
  41. private static void swap(DutchColors[] arr, int a, int b) {
  42. DutchColors tmp = arr[a];
  43. arr[a] = arr[b];
  44. arr[b] = tmp;
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement