Select Sort. Θ(n^2)

Consider sorting n numbers stored in array A by first finding the smallest element of A and exchanging it with the element in A[1] . Then find the second smallest element of A, and exchange it with A[2] . Continue in this manner for the first n 1 elements of A. Write pseudocode for this algorithm, which is known as selection sort. What loop invariant does this algorithm maintain? Why does it need to run for only the first n 1 elements, rather than for all n elements? Give the best-case and worst-case running times of selection sort in Θ notation.

///Select Sort. Θ(n^2)
func selectSort<T: Comparable>(_ array: inout [T]) {
    //Already sorted
    guard array.count > 1 else { return }
    
    //Compare and swap
    for i in 0..<array.count-1 {
        var minElementIndex = i
        for j in i+1..<array.count {
            minElementIndex = array[minElementIndex] <= array[j] ? minElementIndex : j
        }
        if i != minElementIndex { swap(&array[minElementIndex], &array[i]) }
    }
}

var s = try Int.randomArray()
selectSort(&s)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,150评论 0 10
  • 又到中秋节,味美香甜的月饼,总是令人抗拒无法拒。怎么控制住,不让中秋后开始痛苦的减肥呢?最关键 是要吃月饼的...
    智生争冠阅读 3,251评论 0 0
  • 人身躯壳几十年,生死富贵命注定。 人性灵魂永长生,有因有果命运好。 个人努力犹可敬,奈何三岁便知老。 要想人生有好...
    A刘世剑阅读 3,680评论 2 2
  • 我总是畅想我的未来,总是不满足于现在的生活,总觉得这都不是我想要的,所以,我要在我不断的尝试中,发展自己最喜欢的。...
    邮差阅读 1,891评论 0 1
  • 文:Shirley就是爽姐 “哇~哇~哇~”,一声声啼哭响彻天际,一个新的生命呱呱落地,从此开始了它充满未知的旅程...
    Shirley是爽姐阅读 1,755评论 2 2