swift 3.0 冒泡排序,插入排序,选择排序,快速排序

var array = [11,3,53,21,34,12,34]

// bubble sort

for i in (0..<array.count) {

    for j in (i..<array.count - 1) {

        if array[j] > array[j + 1] {

            let tmp = array[j]

            array[j] = array[j + 1]

            array[j + 1] = tmp

        }

    }

}

print(array)

// insert sort

for i in (0..<array.count) {

    var key = array[i]

    var j = i - 1

    while j >= 0 {

        if array[j] > key {
            array[j + 1] = array[j]
            array[j] = key
        }

        j -= 1
    }

}

print(array)

//select sort

for i in (0..<array.count - 1) {

//    print(i)

    var index = i

    for j in (i..<array.count) {

        if array[index] > array[j] {

            index = j

        }

    }

    let tmp = array[i]
    array[i] = array[index]
    array[index] = tmp

}

print(array)

quick sort

var array = [66,13,51,76,81,26,57,69,23]


func partition( list:inout [Int],left:Int,right:Int) -> Int{

    var pivot_index = left
    let piovt = list[left]

    for i in (left ... right) {

        print(i)

        if list[i] < piovt {

            pivot_index += 1

            if pivot_index != i {

                swap(&list[pivot_index], &list[i])

            }

        }

    }

    swap(&list[left], &list[pivot_index])
    return pivot_index

}


func quickSortArray( list:inout [Int],left:Int,right:Int) -> Void{

    if left < right {

        let pivot_index = partition(list: &list, left: left, right: right)

        quickSortArray(list: &list, left: left, right: pivot_index - 1)
        quickSortArray(list: &list, left: pivot_index + 1, right: right)
    }
}

quickSortArray(list: &array, left: 0, right: array.count - 1)

quick sort 2

func quicksort<T: Comparable>(_ a: [T]) -> [T] {
    guard a.count > 1 else { return a }
    let pivot = a[a.count/2]
    let less = a.filter { $0 < pivot }
    let equal = a.filter { $0 == pivot }
    let greater = a.filter { $0 > pivot }
    return quicksort(less) + equal + quicksort(greater)
}

let list1 = [ 10, 0, 3, 9, 2, 14, 8, 27, 1, 5, 8, -1, 26 ]
print(quicksort(list1))
阅读更多
版权声明:本文为博主原创文章欢迎分享转载。 https://blog.csdn.net/hi_chen_xingwang/article/details/55192725
个人分类: swift3-0
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭