All about flooble | fun stuff | Get a free chatterbox | Free JavaScript | Avatars    
perplexus dot info

Home > Algorithms
Algorithm requested (Posted on 2013-12-18) Difficulty: 3 of 5
Given an array with random odd and even integers.
Please suggest the most efficient algorithm to put all even numbers on one side and all odd numbers on the other side in this array.

Source: Got an Email from an unknown person.

See The Solution Submitted by Ady TZIDON    
Rating: 4.0000 (1 votes)

Comments: ( Back to comment list | You must be logged in to post comments.)
Some Thoughts Another Algorithm Comment 3 of 3 |
My algorithm looks at four members at a time and makes a single pass through the array.  This will sort the array to have odd values before the even values.

Declare pointers A, B, Y, and Z.  A starts at the first member, B at the second, Y at the second-to-last, and Z at the last.

If the member at A is odd and the member at Z is even, then increment pointers A and B and decrement pointers Y and Z.

If the member at A is odd and the member at Z is odd, then swap the members at B and Z and increment pointers A and B.

If the member at A is even and the member at Z is even, then swap the members at A and Y and decrement pointers Y and Z.

If the member at A is even and the member at Z is odd, then swap the members at A and Z and increment pointers A and B and decrement pointers Y and Z.

Repeat this until only two members remain.  Those last two members are handled in a simple comparison with a swap if needed.

  Posted by Brian Smith on 2016-06-21 11:18:10
Please log in:
Login:
Password:
Remember me:
Sign up! | Forgot password


Search:
Search body:
Forums (0)
Newest Problems
Random Problem
FAQ | About This Site
Site Statistics
New Comments (6)
Unsolved Problems
Top Rated Problems
This month's top
Most Commented On

Chatterbox:
Copyright © 2002 - 2024 by Animus Pactum Consulting. All rights reserved. Privacy Information