the Reverend
the Reverend

Reputation: 12559

Add Sorting Function to CollectionType (Arrays)

I want to add my own sorting functions to Arrays, so Iam trying to extend the CollectionType protocol to add this functionality. This is what I have so far:

extension CollectionType where Generator.Element : Comparable, Index : IntegerType{
    func psoInsertionSort(){

        var key: Generator.Element
        var x, y: Int


        for (x = 0; x < self.count; x++){
            key = self[x]

            for (y = x; y >= 0; y--){
                if key < self[y]{
                    self.removeAtIndex(y+1)
                    self.insert(key, atIndex: y)
                }
            }
        }
    }
}

I need to constraint the Elements from the CollectionType to Comparable to do the actual sorting, I believe there is no problem there.

The problem I'm getting is in the for loop parameters:

for (x = 0; x < self.count; x++){

Binary operator '<' cannot be applied to operands of type 'Int' and 'Self.Index.Distance'

Looks like self.count is of the type Self.Index.Distance, which honestly, I am not even sure if its the same type of Self.Index.

Upvotes: 2

Views: 453

Answers (1)

oisdk
oisdk

Reputation: 10091

You just need to add those as protocol requirements. So, you can either require that the index distance is Int:

Index.Distance == Int 

Or you can change your loop conditions:

for (var x = self.startIndex; x < self.endIndex; x++){

(you would also need to change the protocol requirements to Index == Int, here, and remove the earlier var x declaration)

Alternately, there's a property of collection types that has exactly what you're looking for in that loop:

for x in self.indices

Also, your functions removeAtIndex and insert require not just a CollectionType, but a RangeReplaceableCollectionType.

And the function needs to be marked mutating

Upvotes: 5

Related Questions