Sort an array of integers into odd, then even
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
When dealing with arrays, one common task is sorting their elements to achieve a particular order. In this article, we will focus on sorting an array of integers such that all odd numbers appear before all even numbers. This exercise can improve your understanding of array manipulations and sorting algorithms.
Understanding the Problem
In this task, we aim to reorder an array where all odd numbers precede even numbers. The relative order within the odd or even numbers doesn't need to be preserved unless the problem explicitly requires it. This particular kind of sorting can be achieved efficiently with a two-pointer technique, partitioning methods, or by using built-in array functions tailored to sorting.
Technical Explanation
Two-Pointer Technique
The two-pointer technique provides an efficient approach to solving this problem. The algorithm involves maintaining two indices:
- Left Pointer (`left`): Starts from the beginning of the array.
- Right Pointer (`right`): Starts from the end of the array.
The algorithm proceeds as follows:
- Increment the `left` pointer while the array element at the `left` index is odd.
- Decrement the `right` pointer while the element at the `right` index is even.
- If `left < right` at any point, swap the elements at these two pointers. This operation moves an even number from the left side of the array towards the right, and an odd number from the right side towards the left.
- Repeat until the `left` and `right` pointers meet.
This approach ensures a time complexity of , where is the length of the array, because each element is visited at most once.
Implementation Example
Here is a Python example using the two-pointer technique:
- Time Complexity: The two-pointer approach is optimal for complexity.
- In-place Sorting: Modifies the original array without extra space.
- Stability: Using `sorted()` in Python does preserve the relative order of odd and even numbers due to stability.
Related reading
- Sort array by firstname (alphabetically) in JavaScript
- Sort array in the minimum number of moves
- Sort array of days in javascript
- Sort array with with first half and second half sorted
- Sort ArrayList of custom Objects by property
- Sort Dictionary by keys
- Sort BST in On using constant memory
- Sort Four Points in Clockwise Order

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.