美文网首页Aha! Algorithms
Aha! Algorithms - Bubble Sort

Aha! Algorithms - Bubble Sort

作者: su3 | 来源:发表于2017-03-16 18:05 被阅读0次

《啊哈!算法》第 1 章第 2 节,冒泡排序的 Swift 实现

问题

给学生成绩排序,打印排序后的名字(和成绩)

解决

依次比较相邻的两个学生分数的大小,把低分的放到后面,直到最后一个尚未归位的学生

struct Student {
    let name: String
    let score: Int
}

var array: [Student] = [Student(name: "huhu", score: 5),
                        Student(name: "haha", score: 3),
                        Student(name: "xixi", score: 5),
                        Student(name: "hehe", score: 2),
                        Student(name: "momo", score: 8)]

let count = array.count

//N 个对象排序,只需要循环 N-1 遍
for i in 0..<count-1 {
    //循环比较直到最后一个尚未归位的对象
    for j in 0..<count-1-i {
        if array[j].score < array[j+1].score {
            swap(&array[j], &array[j+1])
        }
    }
}

for item in array {
    print("\(item.name): \(item.score)")
}

冒泡排序的时间复杂度是 O(N2)

代码在 GitHub

相关文章

  • Aha! Algorithms - Bubble Sort

    《啊哈!算法》第 1 章第 2 节,冒泡排序的 Swift 实现 问题 给学生成绩排序,打印排序后的名字(和成绩)...

  • Sort

    Several classic sorting algorithms. Bubble Sort Selection...

  • Aha! Algorithms - Bucket Sort

    《啊哈!算法》第 1 章第 1 节,桶排序的 Swift 实现 问题 班上 5 个同学的考试成绩分别为:5 分,3...

  • 排序算法1:冒泡排序

    数据结构与算法Sorting Algorithms:Bubble Sort 1 基本思路 该算法对一个数组中的相邻...

  • Aha! Algorithms

    1. 涉及的数据结构 栈、队列、链表、树、并查集、堆、图 2. 涉及的算法 排序、枚举、深度和广度优先搜索、图的遍...

  • Bubble Sort

    Bubble Sort Code

  • sorting algorithoms

    Bubble Sort Selection Sort Insertion Sort search : O(n) o...

  • sort

    bubble_sort: select_sort: insert_sort: merge_sort: quick_...

  • Bubble Sort

    Given an array of integers, sort the elements in the arra...

  • Bubble Sort

    冒泡排序,是不断地比较相邻的两个元素,较小的像上冒,较大的向下沉,排序的过程如同水中气泡上升,即两两比较相...

网友评论

    本文标题:Aha! Algorithms - Bubble Sort

    本文链接:https://www.haomeiwen.com/subject/qlijnttx.html