Here i try to swap position of '9', so it comes right after a '4'.
Input : int[] nums1 = { 1, 4, 1, 9 };
Output: [1, 4, 9, 1]
And the code:
int loc4 = 0;
int temp = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 4) {
loc4 = i;
}
if (arr[i] == 9) {
for (int j = i; j > 0; j--) {
temp = arr[i];
arr[i] = arr[loc4 + 1];
arr[loc4 + 1] = temp;
}
}
}
The problem with this code is that once there's multiple 4s and 9s, it ignores the duplicates.
So i tried adding a repetition count and a continue
statement, for when rep count is more than 1, but that doesn't seem to work?
int loc4 = 0;
int temp = 0;
int rep = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 4) {
loc4 = i;
rep++;
}
if (arr[i] == 9) {
for (int j = i; j > 0; j--) {
temp = arr[i];
arr[i] = arr[loc4 + 1];
arr[loc4 + 1] = temp;
if (rep > 1)
continue;
}
}
}
So when my input is: int[] nums2 = { 1, 4, 1, 9, 9, 4, 1 };
My output should be: [1,4,9,1,1,4,9]
And what i'm getting is: [1, 4, 9, 1, 9, 4, 1]
Note that when there're singular 4s and 9s or when they're already in order, nothing will take place.