Given an array of integers containing positive and negative numbers, rearrange it so that all negative numbers are in front, and all positive numbers are in the back row. The relative order between positive and negative numbers remains the same. The expected time complexity is O (n), and the spatial complexity is O (1).
For example: given [ -1,2,-2,3,5,-4], rearranging and then becoming [ -1,-2,-4,2,3,5]
Analysis: 1. The simplest algorithm is O (n^2), where each negative number is moved to the back of the array of negative numbers that preceded it.
2. O (n) algorithm is not thought out for the moment, it seems more difficult, the following gives an O (NLOGN) algorithm. The basic idea is similar to merge Sort. Spatial complexity due to recursion, is O (Logn). However, it can easily be rewritten as an iterative version of bottom-up.
void Main () {int[] nums = new int[] {-1, 2,-2, 3, 5,-4}; Reorder (nums, 0, Nums. LENGTH-1);} Define other methods and classes herepublic void Reorder (int[] nums, int start, int end) {if (start >= end) {R Eturn;} int middle = start + (End-start)/2; Reorder (Nums, start, middle); Reorder (Nums, middle+1, end); Merge (Nums, start, middle, end);} private void Merge (int[] nums, int start, int end) {int i = Start;while (Nums[i] < 0 && i <= end) I++;int j = end;while (Nums[j] >= 0 && J >= start) j--;//Shift the negative part to the Frontif (I < j) {int k = J; while (k>=i && nums[k]<0) k--; Reverse (Nums, I, K); Reverse (NUMS,K+1,J); Reverse (NUMS,I,J);}} private void Swap (int[] nums, int i, int j) {int t = nums[i];nums[i] = nums[j];nums[j] = t;} private void Reverse (int[] nums, int i, int j) {while (I < j) {Swap (Nums, I, j); i++;j--;}}
Below is the bottom-up iteration version. The spatial complexity is O (1).
public void Reorder (int[] nums) { int n = nums. length;for (int size = 1; size < n; size + = size) {for (int. = 0; low < n-size; low+=size+size) { Merge (nums , Low, Math.min (Low+size+size-1, n-1));}}
Rearrange arrays that contain positive and negative numbers