D-A UK
D-A UK

Reputation: 1174

Sorting Arrays Swift

I have an array of integers that represent their own strings.

I know there are simple ways to sort integer arrays, but I needed to make it so that the integers retain their correspondence to the strings.

Here is my current code:

var i = 0
var highestValueObjectInArray = 0
for object in createTimerData.speechTimeStamps {

    if object > highestValueObjectInArray {
        highestValueObjectInArray = object
    }

}

while i + 1 < createTimerData.speechTimeStamps.count {

    if createTimerData.speechTimeStamps[i] < createTimerData.speechTimeStamps[i + 1] {

        let TS2 = createTimerData.speechTimeStamps[i + 1]
        let TSS2 = createTimerData.speechText[i + 1]

        createTimerData.speechTimeStamps.remove(at: i + 1)
        createTimerData.speechTimeStamps.insert(TS2, at: i)
        createTimerData.speechText.remove(at: i + 1)
        createTimerData.speechText.insert(TSS2, at: i)

    }

    i += 1
    if i+1 >= createTimerData.speechTimeStamps.count {

        var lastItem = highestValueObjectInArray + 1
        var inDescendingOrder = true
        for object in createTimerData.speechTimeStamps {
            if object < lastItem {} else { inDescendingOrder = false }
            lastItem = object
        }
        if inDescendingOrder == false {
            i = 0
        }
    }
}

It is very slow and not very efficient so when it sorts large arrays it takes a large amount of time. Is there a way I have overlooked, or a way that is more efficient.

Any help would be much appreciated, thanks.

Upvotes: 1

Views: 107

Answers (2)

Rob
Rob

Reputation: 437392

Often, when you want to sort separate arrays alongside each other, you should really consider merging them into a single array of a custom type. For example, speechText and speechTimestamps might merged into an array of a single type, Speech:

struct Speech { 
    let text: String
    let timestamp: Int
}

let speeches = [
    Speech(text: "Baz", timestamp: 2),
    Speech(text: "Bar", timestamp: 3),
    Speech(text: "Foo", timestamp: 1)
]

Then you can sort these as you see fit:

let result = speeches.sorted { $0.timestamp < $1.timestamp }

Clearly, modify the types and the names as appropriate, but hopefully this will illustrate the idea. Consider a single array of a type that captures both things being sorted.

Upvotes: 3

Malik
Malik

Reputation: 3802

You can zip the two arrays together, sort the zipped array, and then separate them like below

let arr1 = [1,4,2,5,3]
let arr2 = ["One","Four","Two","Five","Three"]

let combined = zip(arr1, arr2).sorted(by: {
    $0.0 < $1.0
})

let sorted1 = combined.map {$0.0}
let sorted2 = combined.map {$0.1}

print(sorted1) // [1, 2, 3, 4, 5]
print(sorted2) // ["One", "Two", "Three", "Four", "Five"]

Upvotes: 2

Related Questions