array sorting
integer sorting
odd even sorting
algorithm
programming technique

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.

Practice algorithms

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:

  1. Left Pointer (`left`): Starts from the beginning of the array.
  2. Right Pointer (`right`): Starts from the end of the array.

The algorithm proceeds as follows:

  1. Increment the `left` pointer while the array element at the `left` index is odd.
  2. Decrement the `right` pointer while the element at the `right` index is even.
  3. 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.
  4. Repeat until the `left` and `right` pointers meet.

This approach ensures a time complexity of O(n)O(n), where nn 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 O(n)O(n) 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
Course
Intermediate
27 lessons
15 hours
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 course
Track 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.

Practice algorithms

All Rights Reserved.