[关闭]
@w1024020103 2017-05-25 11:06 字数 928 阅读 744

Lecture 32: Sorting I

CS61B


The Sorting Problem

Definition

image_1bgssqtkesmc11npd4j1ribeou9.png-107.2kB

An alternative point of view

image_1bgssrpm8pba15a2145ft5gqrdm.png-153.6kB

Performance definitions

image_1bgssurj9iippev6lk1jaug1a13.png-116.3kB

不是很懂这里的“extra"是什么意思

Selection Sort, Heapsort

Selection Sort

image_1bgst9peg552grbft65ie1uo61g.png-81.7kB

Heapsort

Naive Heapsort

Demo

image_1bgstpmn91dmpqs01adrt2q3uc1t.png-44.4kB

Runtime Analysis

image_1bgsttss617m9heddu51puqio32n.png-134.5kB

In-place Heapsort

In-place Heapsort

image_1bgtgql5roa7n4f1uhk6hs1skt34.png-109.7kB

In-place Heapsort Runtime

image_1bgtgurv2gti1gkub7hqoo1poq3h.png-121.8kB

Memory complexity

image_1bgth00rq1bg77i1gus15pnvvi3u.png-97.5kB

这里的Space complexity means auxiliary space complexity.

见讨论

Why does heap sort have a space complexity of O(1)?

image_1bgtjqihh1cfb6id13081a8p1qth9.png-72.8kB

Runtime上还是有很多不懂的!

Mergesort

Runtime analysis Demo
Mergesort demo

Runtime

image_1bguli38l104t11bc1vu9ibv1mqum.png-118.6kB

So far

image_1bgulj7ljd2v16861eb91kd4pf813.png-87.8kB

Insertion Sort

老师说很像你打扑克的时候,每摸到一张牌,自己会按照顺序插到已经拿到的牌里边儿,其实就是一个insertion sort的过程。

Naive approach

从Input里面一个元素一个元素地插入到新的output array里面:
Demo

image_1bguoa1ej14g85vr607gsrt9l1g.png-71.9kB

In-place insertion sort:

Do everything in place using swapping

image_1bguog3ms2lm147sdpq1fmf19h21t.png-31.1kB

Demo

Number of swaps

image_1bguogpug1nqj6qn1hmia1fl752a.png-126kB

Runtime

image_1bguohr1elb4uqa14tn1qnq1gjt3n.png-133.9kB

best case: 如果array是already sorted, 也就是绿色的字母是对角线,那么没有需要swap的,只需要N次compares,runtime是Θ(N);
worst case: 如果每一个字母都需要从当前位置swap到第一位,也就是绿色的字母全部是每一行的第一列,那就相当于所有字母swap过的范围构成了一个等腰三角形,runtime是Θ(N^2)

pick the right sorting method

image_1bguoot13rvk401h9q1pe014fp44.png-121.5kB

Insertion sorting is extremely fast on arrays with a small number of inversions

image_1bguor6l41m1t28s1jc51tgk1csf4h.png-140.9kB

Sorts so far

image_1bguoti4fb6ovdk13gs1mks14e4u.png-118.6kB

Shell’s Sort (Extra)

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注