Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort arrays to make odds before evens

Tags:

swift

Given an array and then sort it to make the odds appearance before evens. So I wrote the method like below in Swift. I can't see anything wrong in this methods, but the logic is just not right. Anybody could give me a clue will save my life. Thanks in advance!

Here's the code:

class OddsBeforeEvens {
    func sortArrayOddsBeforeEvens(var array: [Int]) -> [Int]? {
        if array.isEmpty { return nil }
        let length = array.count
        var begin = 0
        var end = length - 1
        var temp: Int
        while (begin < end) {
            while (begin < end && array[begin] / 2 != 0) {
                begin += 1
            }
            while (begin < end && array[end] / 2 == 0) {
                end -= 1
            }
            if (begin < end) {
                temp = array[begin]
                array[begin] = array[end]
                array[end] = temp
            }
        }

        return array
    }
}   
like image 790
Faye Zhao Avatar asked Dec 10 '22 15:12

Faye Zhao


1 Answers

As an alternative, you can separate the odds and even numbers by two filter operations on the array, and simply join the two resulting arrays, with the odd values arrays prior to the even values array

func sortArrayOddsBeforeEvens(array: [Int]) -> [Int] {
    let odds = array.filter{ $0 % 2 != 0 }
    let evens = array.filter{ $0 % 2 == 0 }
    return odds + evens
}     

print(sortArrayOddsBeforeEvens([1,4,3,7,8,11,12,27,18]))
// [1, 3, 7, 11, 27, 4, 8, 12, 18]

Or,

func sortArrayOddsBeforeEvens(array: [Int]) -> [Int] {
    return array.filter{ $0 % 2 != 0 } + array.filter{ $0 % 2 == 0 }
}     

print(sortArrayOddsBeforeEvens(array: [1,4,3,7,8,11,12,27,18]))
// [1, 3, 7, 11, 27, 4, 8, 12, 18]

This shouldn't be an issue in practice unless you're writing some HPC applications (in which case possible Swift isn't the optimal language of choice), but if you for some reason worry about performance wr.t. the two filter operations above, you could use the result of $0 % 2 (which is always in the set {0, 1}) directly as an index to point at one of two given result arrays. E.g.

func sortArrayOddsBeforeEvens(array: [Int]) -> [Int] {
    var arr: [[Int]] = [[],[]]
    array.forEach { arr[$0 % 2].append($0) }
    return arr[1] + arr[0]
} 

print(sortArrayOddsBeforeEvens([1,4,3,7,8,11,12,27,18]))
// [1, 3, 7, 11, 27, 4, 8, 12, 18]
like image 136
dfrib Avatar answered Jan 24 '23 21:01

dfrib