0

I have an array of sections:

struct Section {
    let title: String
    var items: [Item]
}

Which contains a list of items:

struct Item {
    let title: String
}

I'd like to populate this with an unknown amount of items, and sort the data as efficiently as possible. I fetch the data from a remote source, and parse the data as it comes in. I can't know if the data being sent is sorted or not, so blindly appending to a Section list may not work here.

I'd like the data to be shown to the user as soon as it comes in (in batches), so I can't wait until the end of the fetch operation to perform sorting. For examples sake, lets assume I'm getting the section by:

let item = Item(title: "Foo")
let sectionTitle = item.characters.first!
if let section = sections.filter({ $0.title == String(sectionTitle) }) {
  // find
} else {
  // create
}

My initial idea, once I've figured out the correct Section, loop through the Section items until sectionItem.title > item.title, then that becomes the insertion point:

var insertionPoint = 0
for (i, val) in array.enumerated() {
    insertionPoint = i
    if val.title > item.title { break }
}

section.items.insert(item, at: insertionPoint)

This does seem inefficient once the Section has many Item objects. Is there a more appropriate method?

My only other thought would be to keep track of Section items that were touched in this batch, then running section.items.sort() at the end of each batch operation.

1 Answer 1

1

For each batch of items:

  1. Add each item to a temp array for a section.
  2. Sort each temp array.
  3. Merge the sorted temp array with the already sorted array for the section. Merging two sorted arrays is a very efficient operation.
Sign up to request clarification or add additional context in comments.

2 Comments

That looks like it could work well, do you know what Swift's sort() method uses under the hood?
I'm afraid I don't know the details of Swift's sort.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.