Search code examples
algorithmswiftbubble-sort

Generic Swift Bubblesort Error


I'm trying to implement a version of Bubblesort in Swift, but I keep getting the following error whenever I try to run it:

'T' is not convertible to 'UInt8'

if (list[i] > list[i+1]) {

Does anyone know what's up? I've attached my code below:

func valueSwap<T>(inout value1: T, inout value2: T) {

    let oldValue1 = value1
    value1 = value2
    value2 = oldValue1
}

 func bubblesort<T>(inout list:Array<T>) {
    var swapped:Bool
    do {
        swapped = false
        for i in 0...list.count - 2 {
            if (list[i] > list[i+1]) {
                valueSwap(&list[i], &list[i+1])
                swapped = true
            }
        }
    } while swapped
}

I tried brute casting it but it doesn't seem to work. Any ideas? Thanks!


Solution

  • Just figured it out - all I had to do was confirm that the type conforms to Comparable.

    func bubblesort<T: Comparable>(inout list:Array<T>)