Given an array with positive and negative integers. Re-range it to interleaving with positive and negative integers.
Notice
You are not necessary to keep the original order of positive integers or negative integers.
Example
Given [-1, -2, -3, 4, 5, 6]
, after re-range, it will be [-1, 5, -2, 4, -3, 6]
or any other reasonable answer.
java
public class Solution {
/*
* @param A: An integer array.
* @return: nothing
*/
public void rerange(int[] A) {
// write your code here
if (A == null || A.length == 0) {
return;
}
Arrays.sort(A);
if (A.length % 2 == 0) {
int left = 1;
int right = A.length - 2;
while (left <= right) {
swap(A, left, right);
left += 2;
right -= 2;
}
} else if (A[(A.length - 1) / 2] < 0) {
int left = 1;
int right = A.length - 1;
while (left <= right) {
swap(A, left, right);
left += 2;
right -= 2;
}
} else {
sort(A, 0, A.length - 1);
int left = 1;
int right = A.length - 1;
while (left <= right) {
swap(A, left, right);
left += 2;
right -= 2;
}
}
}
private void sort(int[] nums, int start, int end) {
if (start > end) {
return;
}
int left = start;
int right = end;
int pivot = nums[(start + end) / 2];
while (left <= right) {
while (left <= right && nums[left] > pivot) {
left++;
}
while (left <= right && nums[right] < pivot) {
right--;
}
if (left <= right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
sort(nums, start, right);
sort(nums, left, end);
}
private void swap(int[] nums, int left, int right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
}