Sorting Problem

Segregate Even And Odd Numbers

Problem

Given an array of numbers, rearrange them in-place so that even numbers appear before odd ones.

Example

{
"numbers": [1, 2, 3, 4]
}

Output:

[4, 2, 3, 1]

The order within the group of even numbers does not matter; same with odd numbers. So the following are also correct outputs: [4, 2, 1, 3], [2, 4, 1, 3], [2, 4, 3, 1].

Solution

function swap(arr, i, j) {
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
function segregate_evens_and_odds(numbers) {
    // Write your code here.
    
    //Initialize two index variables left and right
    var j = -1, i=0;
    
    while (i != numbers.length) {
        //If even number swap odd with even
        if(numbers[i]%2 == 0) {
            j++;
            swap(numbers, j, i);
        }
        i++;
    }
    
    return numbers;
}

Time and Space Complexity

Time Complexity : O(n)
Space Complexity:  O(n)

Leave a comment