757
Saw this challenging question posted in the hardwarezone forum on sorting an array with one for loop without using array list.
The question is
This is a simple programming question...very simple and short question, but its really hard to solve.. Anyone who could do it, you are god of programming. Given an array of random numbers let say.. arrayX = {15, 20, 35, 45, 10, 40, 1, 3, 45};You are supposed to use ONLY ONE loop to swap the above into the following: arrayX = {15, 20, 3, 1, 10, 40, 45, 35, 45}; NOTE: The purpose of your loop is to move all digits < 25 from the right hand side to the left side, and move all digits >= 25 to the right side. You can't sort the array but to use a single loop to scan the array from left and scan the array from right...and do the necessary swapping. You can try do it with C, C++...etc.. Not easy as it seems to be!Since the night is still young, I took some time to sit down and figure out the solution.
There are some answers posted in that thread but their answers could not get the exact output out.
One forumer pointed out to have scan each element and put those < 25 into one array and those => into another. This solution can work… but doesnt output that answer.
Here’s my solution in PHP.
<?php $array1 = array(15, 20, 35, 45, 10, 40, 1, 3, 45); $array2 = $array1; $j = sizeof($array2)-1; for ($i=0;$i<$j;$i++) { if ($array1[$i]>$array2[$j]){ if ($array1[$i]>25){ $array2[$i] = $array1[$j]; $array2[$j] = $array1[$i]; $array1 = $array2; $j--; } }else{ $j--; } print_r($array2); echo ("<br/>"); } ?>I upload the php in my site. You can see the output here.
Explanation
- Duplicate the array
- Compare first element of that array with the last element of the second array. The exit condition of the for loop is when the the comparison of the position of both arrays meet.
- If first element > last element, we then further check if it’s > 25. if yes, we swap them.
- If not, we skip to next element in first array but the last element in second array still remains.
That’s it! If you can further improve the codes. Please feel free to comment. Cheers.