702920. Even Greater than Odd
Easy
Even Greater than Odd
Summary
Given an array of integers, rearrange its elements such that even positioned elements are greater than odd positioned elements. This problem involves sorting and manipulation of arrays, making it a classic algorithmic challenge.
Detailed Explanation
To solve this problem, we can use a simple two-pointer approach. We maintain two pointers, i and j, starting from the beginning of the array. The i pointer points to even-indexed elements, while the j pointer points to odd-indexed elements.
Here's the step-by-step breakdown:
- Initialize
iandjto 0. - While
i < n-1(wherenis the length of the array), do:- If
arr[i] <= arr[j], incrementi. This ensures that even-indexed elements are greater than or equal to odd-indexed elements at this point. - Otherwise, swap
arr[i]andarr[j]. This brings an element from the odd position to an even position, making it possible for the next iteration.
- If
- Repeat step 2 until
i >= n-1. - Return the rearranged array.
The time complexity of this algorithm is O(n), where n is the length of the input array. The space complexity is O(1) since we only use a constant amount of space to store the pointers and temporary variables.
Optimized Solutions
Java
public static int[] evenGreater(int[] arr) {
int i = 0, j = 1;
while (i < arr.length - 1) {
if (arr[i] <= arr[j]) {
i++;
} else {
swap(arr, i, j);
}
j = i + 2;
}
return arr;
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}