Main Page
 The gatekeeper of reality is
 quantified imagination.

Stay notified when site changes by adding your email address:

Your Email:

Bookmark and Share
Email Notification
sortBinaryArray [Go Back]
Purpose
The purpose of this script is to sort a "binary" array so that 0's preceed 1's. 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 "Binary" Array Question (and answer):
Given the "binary" array [0,1,1,0,0,1,0,0,1], arrange it so that 0's preceed 1's.
For reference, the value returned should be: [0,0,0,0,0,1,1,1,1]

Function Logic Output:


Full Working Code You Can Copy:
<html>
<head>
<script language="javascript" type="text/javascript">
function sortBinaryArray(sequence) {
	/* Sort the sequence passed to this function */
	sequence.sort(function(a, b) {return a - b});
	return(sequence);
}
</script>
</head>
<body onload='javascript:document.getElementById("output").value = sortBinaryArray([0,1,1,0,0,1,0,0,1]);'>
	Given the "binary" array [0,1,1,0,0,1,0,0,1], arrange it so that 0's preceed 1's.<br />
	<span style="font-size:9pt">For reference, the value returned should be: [0,0,0,0,0,1,1,1,1]</span>
	<br /><br />
	<strong>Function Logic Output:</strong><br />
	<textarea name="output" id="output" rows="4" cols="30"></textarea>
</body>
</html>
About Joe