Skip to content

Instantly share code, notes, and snippets.

@NZhuravlev
Created April 20, 2021 09:59
Show Gist options
  • Save NZhuravlev/af954f24c69615cf97431cff9ead6481 to your computer and use it in GitHub Desktop.
Save NZhuravlev/af954f24c69615cf97431cff9ead6481 to your computer and use it in GitHub Desktop.
class Solution {
// temp: input array
// n: size of array
//Function to rearrange the array elements alternately.
public static void rearrange(int arr[], int n){
for (int i = 0; i < arr.length; i++) {
int index = i;
int next = arr[index];
if (next < 0) continue;
index = newIndex(index, arr.length);
while (index != i) {
int tmp = arr[index];
arr[index] = -next;
next = tmp;
index = newIndex(index, arr.length);
}
arr[index] = -next;
}
for (int i = 0; i < arr.length; i++) {
arr[i] = -arr[i];
}
}
private static int newIndex(int i, int size) {
int ordinal = i + 1;
return ordinal > size / 2 ? 2 * (size - i - 1) : ordinal * 2 - 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment