This is the question I am looking at:
Given an unsorted array Arr of N positive and negative numbers. Your task is to create an array of positive and negative numbers without changing the relative order of positive and negative numbers.
So, here's what my naive mind thought! I use a variation of insertion sort.
Here is the code:
void reorder(int arr[], int n) {
for (int i = 0; i < n; i++) {
int hole = i;
while ((arr[hole] < 0) && (hole > 0)) {
int temp = arr[hole];
arr[hole] = arr[hole - 1];
arr[hole - 1] = temp;
hole--;
}
}
}
This code changes the relative position of negative numbers, which is not desired. How can I avoid doing that in my code?
Example
Input:
arr = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
Expected result:
-12 -13 -5 -7 -3 -6 11 6 5
But my result is:
-6 -3 -7 -5 -13 -12 11 6 5