算法 - 数组排序(两边扩散取数据)

12 阅读1分钟

概述: 从数组 a 取数据, 得到一个数组b, 取数的规则是, 给定一个索引值 index, 得到数组b, 先从index + 1出取一个数, 放到数组b, 再从 index - 1处, 取一个数放到数组b, 依次循环。如果数组a 左边没有元素了, 就从右边取, 如果数组a 右边没有元素了, 就从左边取, 直到左右两边没有元素为止, 但是前提是取够10个元素就停止

eg1:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

index = 4

b = [6,4,7,3,8,2,9,1,10,11] 

算法如下

func generateArrayB(from arrayA: [Int], withIndex index: Int) -> [Int] {
        var arrayB = [Int]()
        
        var lowerIndex = index - 1
        var upperIndex = index + 1

        while arrayB.count < 10 && (lowerIndex >= 0 || upperIndex < arrayA.count) {
            if arrayB.count < 10 && upperIndex < arrayA.count {
                arrayB.append(arrayA[upperIndex])
                upperIndex += 1
            }

            if lowerIndex >= 0 {
                arrayB.append(arrayA[lowerIndex])
                lowerIndex -= 1
            }
        }
        return arrayB
    }

使用

let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
let index = 4
let b = generateArrayB(from: a, withIndex: index)
print(b) // Output: [6, 4, 7, 3, 8, 2, 9, 1, 10, 11]