arrays - 按数字顺序在数组中插入 Int

标签 arrays swift sorting

<分区>

这是一个小数学/编码问题。

我正在尝试找出在 Int 数组中插入 Int 的最佳方法,该数组位于正确的索引处,以使数组按从低到高的数字顺序排列。

一种方法是遍历数组,一旦索引 +1 > 大于我的数字就将其插入索引。

我想知道有没有什么快捷的方法。

类似于:

let index = array.index(where: { ($0 < number && $1 > number) } )

虽然我不能向闭包添加两个参数...

有什么想法吗?

最佳答案

只要数组开始为空或保持排序,下面的代码就可以将新数字插入到正确的位置:

var ints = [3,6,9,15,20]
var num = 12
ints.insert(num, at: ints.index(where: {$0 > num}) ?? ints.endIndex)
print(ints)

num = 2
ints.insert(num, at: ints.index(where: {$0 > num}) ?? ints.endIndex)
print(ints)

num = 24
ints.insert(num, at: ints.index(where: {$0 > num}) ?? ints.endIndex)
print(ints)

输出:

[3, 6, 9, 12, 15, 20]
[2, 3, 6, 9, 12, 15, 20]
[2, 3, 6, 9, 12, 15, 20, 24]

显然,您希望将它变成一个函数或将其放在一个扩展中,这样您就不需要不断重复同一行。

关于arrays - 按数字顺序在数组中插入 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44222571/

相关文章:

C# List.Sort 不排序

algorithm - 我们能否合并来自相似数据集的排名以产生全局排名?

c - 为什么 printf() 在打印多个字符串 (%s) 时会留下换行符以及如何解决这个问题?

c - 读取文件并存储在数组中

c++ - char[] 和 int[] 的区别

ios - FBSDKLog : FBSDKGraphRequestConnection cannot be started before Facebook SDK initialized

python - 在字典中的字典中返回特定列表的最快方法是什么?

python - numpy中 'invalid value encountered in less_equal'的原因可能是什么

swift - iOS 图表 : Determine Circle Position on chartValueSelected()

swift - Rx swift : What is the best practice to use DisposeBag?