Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. /*
  2.  
  3. Given an array numbers, write a java function to move all 0's to the end of
  4. it while maintaining the relative order of the non-zero elements.
  5. You must do this in-place without making a copy of the array.
  6. Minimize the total number of operations.
  7. Example:
  8.  
  9. Input: {0,1,0,12,11}
  10. Output: {1,12,11,0,0}
  11.  
  12. */
  13.  
  14. public class AlogProblem {
  15.  
  16. public static void moveZeros(int [] numbers) {
  17. final int value = 0;
  18.  
  19.  
  20. int arrLength = numbers.length;
  21. int i = arrLength - 1;
  22. int current ;
  23. int temp;
  24. while( 0 <= i) {
  25. if(numbers[i] == value) {
  26. temp = numbers[i];
  27. current = i;
  28. do {
  29. int index = current + 1;
  30. if(index == arrLength) break;
  31. if(numbers[index] != value) {
  32. numbers[current] = numbers[index];
  33. numbers[index] = temp;
  34. current++;
  35. } else {
  36. break;
  37. }
  38.  
  39.  
  40.  
  41. } while(true);
  42. }
  43. i--;
  44. }
  45.  
  46. }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement