1

Here's a little mathematical/coding question.

I'm trying to figure out the best way of inserting a Int within an array of Ints at the correct index for the array to be in numerical order lowest-highest.

One way would be to loop over the array and as soon as index +1 > than my number than insert it at index.

I wondered though if there was any kind of swifty way.

Something like:

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

I can't add two parameters to the closure though...

Any ideas?

Sammy The Hand
  • 175
  • 1
  • 11
  • Not really a "Swifty" approach but you could use `NSOrderedSet` assuming your numbers are unique. – rmaddy May 27 '17 at 23:56
  • Why not just add it to the array, than dort the array? Performance-wise this shouldn't be worse than finding the right index and insert it there, as all values at higher indices must be moved. – vikingosegundo May 28 '17 at 00:05
  • 1
    Algorithmically, you'd want to find the insertion point with a binary search. That way, if your array has 1024 items, you could identify the insertion point with ~10 compares compared to 512 on average if you search sequentially. – vacawama May 28 '17 at 00:22

1 Answers1

1

As long as the array starts empty or remains sorted, the following code can insert the new number into the correct location:

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)

Output:

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

Obviously you would want to make this into a function or put it in an extension so you don't need to keep repeating that same line over.

rmaddy
  • 314,917
  • 42
  • 532
  • 579