Created
April 20, 2021 09:59
-
-
Save NZhuravlev/af954f24c69615cf97431cff9ead6481 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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