题解 | #对其元素按照升序或降序进行排序#

输入整型数组和排序标识,对其元素按照升序或降序进行排序

https://www.nowcoder.com/practice/dd0c6b26c9e541f5b935047ff4156309?tpId=37&tqId=21324&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fdifficulty%3D1%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D37%26type%3D37&difficulty=1&judgeStatus=undefined&tags=&title=

import Foundation

while let line = readLine() {
    
    var array = readLine()!.components(separatedBy: " ")
    let flag = Int(String(readLine()!))!

    for i in 0..<array.count {
        for j in 0..<array.count-i-1 {
            let first = Int(array[j])!
            let second = Int(array[j+1])!

            if (first > second) && flag == 0 {
                array.swapAt(j,j+1)
            } else if (first < second) && flag == 1 {
                array.swapAt(j,j+1)
            }
        }
    }
   
    print(array.joined(separator:" "))
}

全部评论

相关推荐

人来疯的伊登等一个offer:轮抽象,还得看我这个,我甚至消息都没发😂查看图片
点赞 评论 收藏
分享
牛客263158796号:我领羊一面后十天不挂也不推进 今天问hr说等前序的第一批意向发完看情况再看是否推进
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务