PROBLEM
Write a program to sort any given integer array of positive and negative numbers such that positive numbers follow negative numbers, however relative position of positive and negative numbers remains same. Like in the example below (1), (-7) occurs after (-5) hence in sorted array (-7) follows (-5).
The program should iterate given array only once and should not use temporary array.
Example 1. Given Array: { 2, 4, -5, 0, -7, -2, 2, -5, 1, -9, -7, -1 }
Sorted Array: { -5, -7, -2, -5, -9, -7, -1, 2, 4, 0, 2, 1 }
Example 2. Given Array: { -3, 7, 0, -2, -1, 3, -3, 9, 5, -5, 8}
Sorted Array: { -3, -2, -1, -3, -5, 7, 0, 3, 9, 5 , 8}
MY SOLUTION
class Program
{
public static void Main(string[] args)
{
var intArray = new int[] { 2, 4, -5, 0, -7, -2, 2, -5, 1, -9, -7, -1 };
var sorted_intArray = SortIntArray(intArray);
Console.WriteLine(String.Join(",", sorted_intArray));
intArray = new int[] { -3, -2, -1, -3, -5, 7, 0, 3, 9, 5, 8 };
sorted_intArray = SortIntArray(intArray);
Console.WriteLine(String.Join(",", sorted_intArray));
Console.ReadLine();
}
private static int[] SortIntArray(int[] intArray)
{
var sorted_intArray = intArray.GroupBy(_int => _int < 0 ? -1 : 1)// Create group of +ve and -ve numbers
.OrderBy(group => group.Key) // Bring group of -ve number first
.SelectMany(groupedItems => groupedItems).ToArray(); // Select num from both Group and convert to array
return sorted_intArray;
}
}
QUESTION
i) The problem statement says , numbers should be iterated only once and temporary array should not be used. I believe my solution using linq do not meet this requirement. How to solve mentioned problem with linq , if possible?
ii) What could be other possible and efficient ways to solve mentioned problem with or without linq? Solution using C/C++ is also fine.