Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. package pocketmath.exercise.first;
  2.  
  3. /**
  4. * Created by curryshih on 2/19/17.
  5. */
  6.  
  7. /**
  8. * Time Complexity: O(n), and operate in-place with only a constant amount of extra space.
  9. * This function segregates evens and odds,
  10. * but it doesn't produce the output in exactly the same order as this sample.
  11. *
  12. * sample input : 2,4,7,6,1,3,5,4
  13. * sample output : 2,4,6,4,7,1,3,5
  14. */
  15.  
  16. public class EvenOddSort {
  17. static void orderEvenOdd(int items[])
  18. {
  19. /* Initialize left and right indexes */
  20. int left = 0;
  21. int right = items.length - 1;
  22. while (left < right) {
  23. /* increase left index if it's even */
  24. while (items[left]%2 == 0 && left < right) {
  25. left++;
  26. }
  27.  
  28. /* decrease right index if it's odd */
  29. while (items[right]%2 == 1 && left < right) {
  30. right--;
  31. }
  32.  
  33. if (left < right) {
  34. //Swap item[left] and item[right]
  35. int temp = items[left];
  36. items[left] = items[right];
  37. items[right] = temp;
  38. left++;
  39. right--;
  40. }
  41. }
  42. }
  43.  
  44. public static void main(String[] args)
  45. {
  46. int items[] = {2,4,7,6,1,3,5,4};
  47. orderEvenOdd(items);
  48. System.out.print("Array after reorder: ");
  49. for (int i = 0; i < items.length; i++)
  50. System.out.print(items[i]+" ");
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement