Edit (5/29/2015): I overlooked the requirement to maintain the order of appearance, so the answer below does not satisfy all the requirements of the question. However, I leave the original answer for general interest.
This is a special version of the very important quicksort routine, known as the "partition". Definition: an array A containing N numeric entries is divided by the value K in the index p if A [i] K for 0 <= i <p and A [j]> = K for p <= j <N if all entries less than K (which means p = N) or not less than K (which means p = 0). For the problem under consideration, we will partition the array around K = 0.
You can split an unsorted array into any K value O (n) times by accessing each record in the array only once, using O (1) extra memory. Informally, you go through an array from both ends, moving values ββthat are on the wrong side. Perform a swap when one inappropriate value is found on each side of the array, and then continues step by step. Now C ++ code:
// Assume array A[] has size N int K = 0; // For particular example partitioning positive and negative numbers int i = 0, j = N-1; // position markers, start at first and last entries while(1) { // Break condition inside loop while(i < N && A[i] < K) i++; // Increase i until A[i] >= K while(j >= 0 && A[j] >= K) j--; // Decrease j until A[j] < K if(i < j) swap(A[i],A[j]); else break; } // A[] is now partitioned, A[0]...A[j] < K, unless i==0 (meaning all entries >= K).
Note that if all elements are equal to K (in this case, zero), I never increase and j = 0 at the end. A statement of the problem suggests that this will never happen. The section is very fast and efficient, and this efficiency is the reason why quicksort is the most popular sorting procedure for large arrays. The swap function can be std :: swap in C ++ or you can easily write your own:
void swap(int& a, int& b) { int temp = a; a = b; b = temp; }
Or just for fun, the numbers can be replaced with a place without temporary memory, although remember to overflow:
There are many separation options for special cases, such as a tripartite section for [elements <K] [elements == K] [elements> K]. The quick sort algorithm recursively solves the section, and the value of the K section is usually the first record in the current basement or calculated from several records (for example, the median of three). See Textbooks: Sedgewick and Wayne Algorithms (4th ed., P. 288) or The Art of Computer Programming. 3 from Knut (2nd ed., P. 113).