Arranging Array
Any algorithm suggestion? As you see, task is putting all 9s next to 4(for each 4 there is one 9) I did, but it just rearranges last 9. Thank you in advance! import java.util.Arrays; public class Task4 { public static void main(String[] args) { int [] nums1 = {1,4,1,9}; int [] nums2 = {1,4,1,9,9,4,1}; int [] nums3 = {4,2,2,9}; nums1 = order49(nums1); nums2 = order49(nums2); nums3 = order49(nums3); System.out.println(Arrays.toString(nums1)); // [1,4,9,1] System.out.println(Arrays.toString(nums2)); // [1,4,9,1,1,4,9] System.out.println(Arrays.toString(nums3)); // [4,9,2,2] } public static int[] order49(int[] a) { for (int i = 0; i < a.length; i++) { if (a[i] == 4) { for (int j = 0; j < a.length; j++) { if (a[j] == 9) swap(a, i + 1, j); } } } return a; } public static void swap(int[] a, int p1, int p2) { int temp = a[p1]; a[p1] = a[p2]; a[p2] = temp; } }