Purpose
The purpose of this script is to sort an array with positive and negative values so that those values will be ordered in an alternating positive/negative manner. Over the decades of programming I've never needed to solve such a task but I was asked about it so I provide one approach (using javascript) below.
Sort the Positive/Negative Array in an Alternating Fashion Question (and answer):
Given an array of positive and negative numbers [-1,6,9,-4,-10,-9,8,8,4], sort the array in a way that the first element will be positive, followed a negative one in alternating order. The original order of the array must be preserved and no element may be reused.
For reference, the value returned should be: [6,-1,9,-4,8,-10,8,-9,4]
Function Logic Output:
Full Working Code You Can Copy:
<html>
<head>
<script language="javascript" type="text/javascript">
function alternateSignArray(sequence) {
var resultSequence = [];
/* Isolate positive and negative numbers */
var negativeNumbers = [], positiveNumbers = [];
for (var i = 0; i < sequence.length; i++) {
if (Math.sign(sequence[i]) == 1) {
positiveNumbers.push(sequence[i]);
}
else {
negativeNumbers.push(sequence[i]);
}
}
/* Create sign alternating array with a positive first element */
for (var p = 0; p < positiveNumbers.length; p++) {
resultSequence.push(positiveNumbers[p]);
if (p <= (negativeNumbers.length - 1)) {
resultSequence.push(negativeNumbers[p]);
}
}
return(resultSequence);
}
</script>
</head>
<body onload='javascript:document.getElementById("output").value = alternateSignArray([-1,6,9,-4,-10,-9,8,8,4]);'>
Given an array of positive and negative numbers [-1,6,9,-4,-10,-9,8,8,4], sort the array in a way that the first element will be positive, followed a negative one in alternating order. The original order of the array must be preserved and no element may be reused.<br />
<span style="font-size:9pt">For reference, the value returned should be: [6,-1,9,-4,8,-10,8,-9,4]</span>
<br /><br />
<strong>Function Logic Output:</strong><br />
<textarea name="output" id="output" rows="4" cols="30"></textarea>
</body>
</html>