Chapter 8 Sorting. Content Points  Introduction and Notation Introduction and Notation  Insertion Sort Insertion Sort  Selection Sort Selection Sort.

Slides:



Advertisements
Similar presentations
首 页 首 页 上一页 下一页 本讲内容 投影法概述三视图形成及其投影规律平面立体三视图、尺寸标注 本讲内容 复习: P25~P31 、 P84~P85 作业: P7, P8, P14[2-32(2) A3 (1:1)]
Advertisements

第八章 轴系零件 § 8-1 键、销及其连接 一、键连接 二、销连接 § 8-2 轴 一、轴的分类和应用 二、轴的结构和轴上零件的固定
第十二章 常微分方程 返回. 一、主要内容 基本概念 一阶方程 类 型 1. 直接积分法 2. 可分离变量 3. 齐次方程 4. 可化为齐次 方程 5. 全微分方程 6. 线性方程 类 型 1. 直接积分法 2. 可分离变量 3. 齐次方程 4. 可化为齐次 方程 5. 全微分方程 6. 线性方程.
ISOM MIS 215 Module 7 – Sorting. ISOM Where are we? 2 Intro to Java, Course Java lang. basics Arrays Introduction NewbieProgrammersDevelopersProfessionalsDesigners.
1 Data Structures CSCI 132, Spring 2014 Lecture 31 Merge Sort Analysis Quick Sort.
Chapter 8 SORTING. Outline 1. Introduction and Notation 2. Insertion Sort 3. Selection Sort 4. Shell Sort 5. Lower Bounds 6. Divide-and-Conquer Sorting.
Chapter 8: Sorting. Contents Algorithms for Sorting List (both for contiguous lists and linked lists) –Insertion Sort –Selection Sort –Bubble / Quick.
第 12 章位运算 C 语言兼具高级语言及低级语言的特性,因此 适合编写系统软件。 C 语言具备低级语言的特性 就在于它能直接对硬件进行操作,即位运算。 所谓位运算是指,按二进制位进行的运算。 例如,将一个存储单元中各二进位左移或右移一 位等。
数据挖掘实验 1 Apriori 算法编程实现. 数据挖掘实验一 (20’) 实验目的:了解关联规则在数据挖掘中的 应用,理解和掌握关联挖掘的经典算法 Apriori 算法的基本原理和执行过程并完成程 序设计。 实验内容:对给定数据集用 Apriori 算法进行 挖掘,找出其中的频繁集并生成关联规则。
HistCite 结果分析示例 罗昭锋. By:SC 可能原因:文献年度过窄,少有相互引用.
实验:验证牛顿第二定律. 1 、实验目的:探究 a 与 F 、 m 的定量关系 2 、实验原理:控制变量法 A 、 m 一定时,探究 a 随 F 的变化关系 B 、 F 一定时, 探究 a 随 m 的变化关系.
细分曲面 傅孝明 SA 目录 细分曲面的基本思想 两个关键问题 一些基本概念 几种简单的细分曲面算法 细分曲面方法分类.
一、拟合优度检验 二、变量的显著性检验 三、参数的置信区间
第 4 章 抽象解释 内容概述 以一种独立于编程语言的方式,介绍抽象解释的 一些本质概念 – 将 “ 程序分析对语言语义是正确的 ” 这个概念公式 化 – 用 “ 加宽和收缩技术 ” 来获得最小不动点的较好的 近似,并使所需计算步数得到限制 – 用 “ 伽罗瓦连接和伽罗瓦插入 ” 来把代价较大的属 性空间用代价较小的属性空间来代替.
吉林大学远程教育课件 主讲人 : 杨凤杰学 时: 64 ( 第六十二讲 ) 离散数学. 最后,我们构造能识别 A 的 Kleene 闭包 A* 的自动机 M A* =(S A* , I , f A* , s A* , F A* ) , 令 S A* 包括所有的 S A 的状态以及一个 附加的状态 s.
1 为了更好的揭示随机现象的规律性并 利用数学工具描述其规律, 有必要引入随 机变量来描述随机试验的不同结果 例 电话总机某段时间内接到的电话次数, 可用一个变量 X 来描述 例 检测一件产品可能出现的两个结果, 也可以用一个变量来描述 第五章 随机变量及其分布函数.
吉林大学远程教育课件 主讲人 : 杨凤杰学 时: 64 ( 第三十八讲 ) 离散数学. 第八章 格与布尔代数 §8.1 引 言 在第一章中我们介绍了关于集 合的理论。如果将 ρ ( S )看做 是集合 S 的所有子集组成的集合, 于是, ρ ( S )中两个集合的并 集 A ∪ B ,两个集合的交集.
离子交换的基本理论 郑好转 化学 5 班 唐南理论 唐南理论把离子交换树脂看作是一种具有弹 性的凝胶, 它能吸收水分而溶胀. 溶胀后的离子 交换树脂的颗粒内部可以看作是一滴浓的电解 质溶液. 树脂颗粒和外部溶液之间的界面可以看 作是一种半透膜, 膜的一边是树脂相, 另一边为 外部溶液.
第十一章 曲线回归 第一节 曲线的类型与特点 第二节 曲线方程的配置 第三节 多项式回归.
2.4 基本设计表达式 随机变量的统计特征值 结构的可靠性与可靠 基本设计表达式.
线性代数习题课 吉林大学 术洪亮 第一讲 行 列 式 前面我们已经学习了关 于行列式的概念和一些基本 理论,其主要内容可概括为:
数 学 系 University of Science and Technology of China DEPARTMENT OF MATHEMATICS 第 3 章 曲线拟合的最小二乘法 给出一组离散点,确定一个函数逼近原函数,插值是这样的一种手段。 在实际中,数据不可避免的会有误差,插值函数会将这些误差也包括在内。
OS 进程调度模拟演示 制作人: 钱晶 高上上. OS 进程调度模拟-实验原理 静态优先级原理 在这种方式下,系统一旦把处理机分配给就绪队 列中的优先权最高的进程后,该进程便一直执行下去, 直至完成。或因为发生某事件使该进程放弃处理机,系 统方可再将处理机分配给另一优先级最高的进程。这些 事件包括有优先级更高的进程进入,或是因为某些原因.
第二章 贝叶斯决策理论 3学时.
流态化 概述 一、固体流态化:颗粒物料与流动的流体接触,使颗粒物料呈类 似于流体的状态。 二、流态化技术的应用:流化催化裂化、吸附、干燥、冷凝等。 三、流态化技术的优点:连续化操作;温度均匀,易调节和维持; 气、固间传质、传热速率高等。 四、本章基本内容: 1. 流态化基本概念 2. 流体力学特性 3.
非均相物系的分离 沉降速度 球形颗粒的 :一、自由沉降 二、沉降速度的计算 三、直径计算 1. 试差法 2. 摩擦数群法 四、非球形颗粒的自由沉降 1. 当量直径 de :与颗粒体积相等的圆球直径 V P — 颗粒的实际体积 2. 球形度  s : S—— 与颗粒实际体积相等的球形表面积.
量子化学 第四章 角动量与自旋 (Angular momentum and spin) 4.1 动量算符 4.2 角动量阶梯算符方法
化学系 3 班 何萍 物质的分离原理 世世界上任何物质,其存在形式几乎均以混合 物状态存在。分离过程就是将混合物分成两 种或多种性质不同的纯物质的过程。 分分子蒸馏技术是一种特殊的液-液分离技术。
数 学 系 University of Science and Technology of China DEPARTMENT OF MATHEMATICS 第 5 章 解线性方程组的直接法 实际中,存在大量的解线性方程组的问题。很多数值方 法到最后也会涉及到线性方程组的求解问题:如样条插值的 M 和.
主讲教师:陈殿友 总课时: 124 第十一讲 极限的运算法则. 第一章 二、 极限的四则运算法则 三、 复合函数的极限运算法则 一 、无穷小运算法则 机动 目录 上页 下页 返回 结束 §5 极限运算法则.
第一节 相图基本知识 1 三元相图的主要特点 (1)是立体图形,主要由曲面构成; (2)可发生四相平衡转变; (3)一、二、三相区为一空间。
9的乘法口诀 1 .把口诀说完全。 二八( ) 四六( ) 五八( ) 六八( ) 三七( ) 三八( ) 六七( ) 五七( ) 五六( ) 十六 四十八 四十二 二十四 二十一 三十五 四十 二十四 三十 2 .口算, 并说出用的是哪句口诀。 8×8= 4×6= 7×5= 6×8= 5×8=
量子力学教程 ( 第二版 ) 3.4 连 续 谱 本 征 函 数 的 归 一 化 连续谱本征函数是不能归一化的 一维粒子的动量本征值为的本征函数 ( 平面波 ) 为 可以取 中连续变化的一切实数值. 不难看出,只要则 在量子力学中, 坐标和动量的取值是连续变化 的 ; 角动量的取值是离散的.
吉林大学远程教育课件 主讲人 : 杨凤杰学 时: 64 ( 第五十三讲 ) 离散数学. 定义 设 G= ( V , T , S , P ) 是一个语法结构,由 G 产生的语言 (或者说 G 的语言)是由初始状态 S 演绎出来的所有终止符的集合, 记为 L ( G ) ={w  T *
编译原理总结. 基本概念  编译器 、解释器  编译过程 、各过程的功能  编译器在程序执行过程中的作用  编译器的实现途径.
 符号表  标识符的作用: 声明部分:定义了各种对象及对应的属性和 使用规则。 程序体:对所定义的对象进行各种操作。 $ididname IdnameAttributeIR  必要性 Token : 新表-符号表(种类、类型等信息):
初中几何第三册 弦切角 授课人: 董清玲. 弦切角 一、引入新课: 什么是圆心角、圆周角、圆周角定理的内容是什么? 顶点在圆心的角叫圆心角。 顶点在圆上,并且两边都和圆相交的角叫做圆周角。 定理:一条弧所对的圆周角等于它所对的圆心角的一半。 A B′ C B O.
Department of Mathematics 第二章 解析函数 第一节 解析函数的概念 与 C-R 条件 第二节 初等解析函数 第三节 初等多值函数.
网上预约集港操作指南 一、登录系统 登陆下面图片显示网址:输入堆场用户名、密码和校验码登陆系统.
首 页 首 页 上一页 下一页 本讲内容本讲内容 视图,剖视图(Ⅰ) 复习: P107 ~ P115 作业: P48(6-2,6-4), P49( 去 6-6) P50, P51(6-13), P52 P50, P51(6-13), P52 P53 (6-18,6-20) P53 (6-18,6-20)
1-4 节习题课 山东省淄博第一中学 物理组 阚方海. 2 、位移公式: 1 、速度公式: v = v 0 +at 匀变速直线运动规律: 4 、平均速度: 匀变速直线运动 矢量式 要规定正方向 统一单位 五个量知道了三 个量,就能求出 其余两个量 3 、位移与速度关系:
《 UML 分析与设计》 交互概述图 授课人:唐一韬. 知 识 图 谱知 识 图 谱知 识 图 谱知 识 图 谱.
Chapter 8 SORTING 1. Introduction and Notation 2. Insertion Sort 3. Selection Sort 4. Shell Sort 5. Lower Bounds 6. Divide-and-Conquer Sorting.
Sorting. We live in a world obsessed with keeping information, and to find it, we must keep it in some sensible order. You learned in the last chapter.
CHAPTER 8 SORTING 【学习内容】 【学习内容】 BASIC CONCEPTS 1. Introduction and Notation 2. Insertion Sort 3. Selection Sort 4. Shell Sort 5. Lower Bounds 6. Divide-and-Conquer.
1 Data Structures CSCI 132, Spring 2014 Lecture 30 Comparison trees, Merge Sort.
Chapter 8 Algorithms. Understand the concept of an algorithm. Define and use the three constructs for developing algorithms: sequence, decision, and repetition.
1 、如果 x + 5 > 4 ,那么两边都 可得 x >- 1 2 、在- 3y >- 4 的两边都乘以 7 可得 3 、在不等式 — x≤5 的两边都乘以- 1 可得 4 、将- 7x — 6 < 8 移项可得 。 5 、将 5 + a >- 2 a 移项可得 。 6 、将- 8x < 0.
Data Structures Using C++ 2E Chapter 10 Sorting Algorithms.
名探柯南在侦查一个特大盗窃集团过程 中,获得藏有宝物的密码箱,密码究竟 是什么呢?请看信息: ABCDEF( 每个字 母表示一个数字 ) A :是所有自然数的因数 B :既有因数 5 ,又是 5 的倍数 C :既是偶数又是质数 D :既是奇数又是合数 EF :是 2 、 3 、 5 的最小公倍数.
项目七: PLC 功能指令应用 带进位循环左移指令 XXXXX. 项目七: PLC 功能指令应用 FX2 系列可编程控制器移位控制指令有移位、循环移位、字移位 及先进先出 FIFO 指令等 10 条指令。 带进位循环右移指令 RCR 带进位循环左移指令 RCL 字右移位指令 WSFR 先入先出读出指令.
1 物体转动惯量的测量 南昌大学理学院
§10.2 对偶空间 一、对偶空间与对偶基 二、对偶空间的有关结果 三、例题讲析.
表单自定义 “ 表单自定义 ” 功能是用于制作表单的 工具,用数飞 OA 提供的表单自定义 功能能够快速制作出内容丰富、格 式规范、美观的表单。
7 生产费用在完工产品与在产 品之间分配的核算. 2 第七章 生产费用在完工产品与在产品之 间的分配  知识点 :  理解在产品的概念  掌握生产费用在完工产品与在产品之间的分 配.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
力的合成 力的合成 一、力的合成 二、力的平行四边形 上一页下一页 目 录 退 出. 一、力的合成 O. O. 1. 合力与分力 我们常常用 一个力来代替几个力。如果这个 力单独作用在物体上的效果与原 来几个力共同作用在物体上的效 果完全一样,那么,这一个力就 叫做那几个力的合力,而那几个 力就是这个力的分力。
要求: 熟练掌握发动机的基本术语。 结合实物可以说出发动机大致组成。 掌握发动机的基本工作原理。 掌握发动机各系统的作用。
个体 精子 卵细胞 父亲 受精卵 母亲 人类生活史 问题:人类产生配子(精、卵 细胞)是不是有丝分裂?
逻辑设计基础 1 第 7 章 多级与(或)非门电路 逻辑设计基础 多级门电路.
用 9 加几解决问题 北京小学 石 颖 第八单元 20 以内的进位加法. 一、口算练习,复习旧知 9+5 = 9+7 = 109 快来算一算! 我们一起看算式,抢答结果,看谁算得又对又快! 说一说你是怎么计算 9+5 这道题的。 2+9 = 5+9 =
1 第 4 章 速度瞬心及其应用 ● 利用速度瞬心进行机构的速度分析 ● 将低副机构转变为高副机构 ( 瞬心线机 构,共轭曲线机构) ● 用低副机构的分析方法对高副机构进 行结构和运动分析 ( 高副低代 )
Kruse/Ryba ch081 Object Oriented Data Structures Sorting Insertion Sort Selection Sort Index Sort Shell Sort Divide and Conquer Sort Merge Sort Quick Sort.
八. 真核生物的转录 ㈠ 特点 ① 转录单元为单顺反子( single cistron ),每 个蛋白质基因都有自身的启动子,从而造成在功能 上相关而又独立的基因之间具有更复杂的调控系统。 ② RNA 聚合酶的高度分工,由 3 种不同的酶催化转 录不同的 RNA 。 ③ 需要基本转录因子与转录调控因子的参与,这.
人 有 悲 欢 离 合, 月有阴晴圆缺。月有阴晴圆缺。 华师大版七年级数学第二册 海口市第十中学 数学组 吴锐.
3D 仿真机房建模 哈尔滨工业大学 指导教师:吴勃英、张达治 蒋灿、杜科材、魏世银 机房尺寸介绍.
1 第三章 数列 数列的概念 考点 搜索 ●数列的概念 ●数列通项公式的求解方法 ●用函数的观点理解数列 高考 猜想 以递推数列、新情境下的 数列为载体, 重点考查数列的通 项及性质, 是近年来高考的热点, 也是考题难点之所在.
第二节. 广告牌为什么会被风吹倒? 结构的稳定性: 指结构在负载的作用下 维持其原有平衡状态的能力。 它是结构的重要性质之一。
SCI 数据库检索练习参考 本练习完全依照 SCI 数据库实际检索过程而 实现。 本练习完全依照 SCI 数据库实际检索过程而 实现。 练习中,选择了可以举一反三的题目,读 者可以根据题目进行另外的检索练习,如: 可将 “ 与 ” 运算检索改为 “ 或 ” 、 “ 非 ” 运算检索 等等。 练习中,选择了可以举一反三的题目,读.
§7.2 估计量的评价标准 上一节我们看到,对于总体 X 的同一个 未知参数,由于采用的估计方法不同,可 能会产生多个不同的估计量.这就提出一 个问题,当总体的一个参数存在不同的估 计量时,究竟采用哪一个好呢?或者说怎 样评价一个估计量的统计性能呢?下面给 出几个常用的评价准则. 一.无偏性.
Presentation transcript:

Chapter 8 Sorting

Content Points  Introduction and Notation Introduction and Notation  Insertion Sort Insertion Sort  Selection Sort Selection Sort  Shell Sort Shell Sort  Lower Bounds Lower Bounds  Divide-and-Conquer Sorting Divide-and-Conquer Sorting  Mergesort for Linked Lists Mergesort for Linked Lists  Quicksort for Contiguous Lists Quicksort for Contiguous Lists  Heaps and Heapsort Heaps and Heapsort

Introduction and Notation (概念和符号)  In an external sort, there are so many records to be sorted that they must be kept in external files on disks, tapes, or the like. In an internal sort the records can all be kept internally in high-speed memory. We consider only internal sorting. (内部排序和外部排序)  We use the notation and classes set up in Chapters 6 and 7.Thus we shall sort lists of records into the order determined by keys associated with the records. The declarations for a list and the names assigned to various types and operations will be the same as in previous chapters. (使用第 6 、 7 章中的类,根据记录中的关键字值进行排序。)  If two or more of the entries in a list have the same key, we must exercise special care.

Introduction and Notation  To analyze sorting algorithms, we consider both the number of comparisons of keys and the number of times entries must be moved inside a list, particularly in a contiguous list. (关键字的比较次数及记录的移动次 数)。  Both the worst-case and the average performance of a sorting algorithm are of interest. To find the average, we shall consider what would happen if the algorithm were run on all possible orderings of the list (with n entries, there are n ! such orderings altogether) and take the average of the results. (考 虑最坏情况和平均情形下的排序算法性能)。

Sortable Lists To write efficient sorting programs, we must access the private data members of the lists being sorted. Therefore, we shall add sorting functions as methods of our basic List data structures. The augmented list structure forms a new ADT that we shall call a Sortable_List, with the following form. template class Sortable_list: public List { public: // Add prototypes for sorting methods here. private: // Add prototypes for auxiliary functions here. };  Hence a Sortable_list is a List with extra sorting methods.The base list class can be any of the List implementations of Chapter 6.

Sortable Lists  We use a template parameter class called Record to stand for entries of the Sortable_list.  Any of the Record implementations discussed in Chapter 7 can be supplied, by a client, as the template parameter of a Sortable_list.( 使用与 chapter7 中同样的 record 类和 key 类。 )

INSERTION SORT (插入排序)  Ordered Insertion An ordered_list is an abstract data type, defined as a list in which each entry has a key, and such that the keys are in order; that is, if entry i comes before entry j in the list, then the key of entry i is less than or equal to the key of entry j.

INSERTION SORT For ordered_lists, we shall often use two new operations that have no counterparts for other lists, since they use keys rather than positions to locate the entry. (根据 key 值定位 元素) One operation retrieves an entry with a specified key from the ordered list. Retrieval by key from an ordered list is exactly the same as searching.

INSERTION SORT The second operation, ordered insertion, inserts a new entry into an ordered list by using the key in the new entry to determine where to insert it in the list. Note that ordered insertion is not uniquely specified if the list already contains an entry with the same key as the new entry, since the new entry could go into more than one position.( 当表中已有关 键字相同的记录时,插入的位置是不唯一的。

The chart of ordered insertion

INSERTION SORT  Sorting by Insertion

INSERTION SORT  Contiguous Insertion Sort template void Sortable_list :: insertion_sort( ) /* Post: The entries of the Sortable_list have been rearranged so that the keys in all the entries are sorted into non_decreasing order. Uses: Methods for the class Record ; the contiguous List implementation of Chapter6 */ { int first_unsorted; //position of first unsorted entry int position; //searches sorted part of list Record current; //holds the entry temporarily removed from list

INSERTION SORT for (first_unsorted = 1; first_unsorted < count; first_unsorted++) if (entry[first_unsorted] < entry[first_unsorted - 1]) { position = first_unsorted; current = entry[first_unsorted]; // Pull unsorted entry out of the list. do { // Shift all entries until the proper position is found. entry[position] = entry[position - 1]; position--; //position is empty. } while (position > 0 && entry[position - 1] > current); entry[position] = current; } 是否稳定排序?

对于插入 entry i 来说, i 可以不移动,概率 1/i 也可以移动 1 , 2 , …n-1 个位置 Do while 循环次数 (1+2+3….+i)/(i-1)=i/2 i/2+1 次比较, i/2+2 次移动

INSERTION SORT  Key point of Linked Insertion Sort 1. With no movement of data, there is no need to search from the end of the sorted sublist, as for the contiguous case. (不需移动元素) 2. Traverse the original list, taking one entry at a time and inserting it in the proper position in the sorted list. (每次在已经有序的链表下插入一个新元 素) 3. Pointer last_sorted references the end of the sorted part of the list. 4. Pointer first_unsorted == last_ sorted->next references the first entry that has not yet been inserted into the sorted sublist.

 Key point of Linked Insertion Sort 5. Pointer current searches the sorted part of the list to find where to insert *first_unsorted. 6. If *first_ unsorted belongs before the head of the list, then insert it there. 7. Otherwise, move current down the list until first_unsorted->entry entry and then insert *first_unsorted before *current. To enable insertion before *current, keep a second pointer trailing in lock step one position closer to the head than current. INSERTION SORT

 Key point of Linked Insertion Sort 8. A sentinel( 哨兵 ) is an extra entry added to one end of a list to ensure that a loop will terminate without having to include a separate check. Since last_sorted->next == first_unsorted, the node *first_unsorted is already in position to serve as a sentinel for the search, and the loop moving current is simplified. 9. A list with 0 or 1 entry is already sorted, so by checking these cases separately we avoid trivialities else where.

INSERTION SORT  Linked Insertion Sort template void Sortable_ list :: insertion_sort( ) /* Post: The entries of the Sortable_ list have been rearranged so that the keys in all the entries are sorted into non_decreasing order. Uses: Methods for the class Record, linked List implementation of Chapter 6. */ { Node *first_unsorted, // the first_ unsorted node to be inserted *last_sorted, // tail of the sorted sublist *current, // used to traverse the sorted sublist *trailing; // one position behind current if (head != NULL) { // Otherwise, the empty list is already sorted. Last_sorted = head; // The first node alone makes a sorted sublist. while (last_ sorted->next != NULL) { first_unsorted = last_sorted->next;

INSERTION SORT if (first_unsorted->entry entry) { // Insert*first unsorted at the head of the sorted list Last_sorted->next = first_unsorted->next; first_unsorted->next = head;head = first_unsorted; } else { // Search the sorted sublist to insert *first_unsorted trailing = head; current = trailing->next; while (first_unsorted->entry > current->entry) { trailing = current; current = trailing->next; } // *first_unsorted now belongs between*trailing and*current. if (first_unsorted == current) last_sorted = first_ unsorted; //already in right position else {last_sorted->next =first_unsorted->next; first_unsorted->next = current; trailing->next = first_unsorted;} } } } }

如果链表为空或长度为 1 ,则 无需处理。 // 处理在头部插入的情况 // 处理其他情形 Current 是否稳定排序?

INSERTION SORT  Analysis of contiguous Insertion Sort

INSERTION SORT  Analysis of Insertion Sort The worst case for contiguous insertion sort occurs when the list is in reverse order. Insertion sort verifies that a list is correctly sorted as quickly as any method can.( 插入排序对已正确排序的表排序最快。 )

SELECTION SORT (选择排序)

SELECTION SORT

template void Sortable_list :: selection_sort( ) /* Post: The entries of the Sortable_list have been rearranged so that the keys in all the entries are sorted into non_decreasing order. Uses: max_key,swap. */ { for (int position = count - 1; position > 0; position--) { int max = max_ key(0, position); //if (max!=position) swap(max, position); }

SELECTION SORT  Find maximum key: template int Sortable_list :: max_key(int low, int high) /* Pre: low and high are valid positions in the Sortable_list and low <= high. Post: The position of the entry between low and high with the largest key is returned. Uses: The class Record. The contiguous List implementation of Chapter 6.*/ { int largest, current; largest = low; for (current = low +1; current <= high; current++) if (entry[largest] < entry[current]) largest = current; return largest; }

SELECTION SORT  Swap entries template void Sortable_list :: swap(int low, int high) /* Pre: low and high are valid positions in the Sortable_list. Post: The entry at position low is swapped with the entry at position high. Uses: The contiguous List implementation of Chapter 6. */ { Record temp; temp = entry[low]; entry[low] = entry[high]; entry[high] = temp; }

SELECTION SORT  Analysis and comparison 1 、选择排序的效率与初始状态无关。比较次数为 n ( n-1 ) /2 ,移动 次数为 3 ( n-1 )。 插入排序的效率与初始状态有关,最好情况是当原始数据基本有 序时, (n-1 次比较, 0 次移动)。 2 、由于减少了移动次数,当记录元素较大时,选择排序比插入排 序更为合适。而记录元素较小,移动花费时间不多时,插入排序由 于比较次数少,会更好。

SHELL SORT (希尔排序)  Example

SHELL SORT template void Sortable list :: shell_sort( ) /* Post: The entries of the Sortable_ list have been rearranged so that the keys in all the entries are sorted into nondecreasing order. Uses: sort_interval */ { int increment, //spacing of entries in sublist start; //starting point of sublist increment = count; do { increment = increment/3 + 1; for (start = 0; start < increment; start++) Sort_interval(start, increment); // modified insertion sort } while (increment > 1); }

LOWER BOUNDS  Insertion sort

LOWER BOUNDS  Selection sort 从图中可看出,平均情况下,选择排序的比较次数比插入排序多。

树的高度体现了最坏情况下的比较次数 平均查找次数 = 树的外部路径长度 / 叶结点数 叶结点数至少为 n ! 根据 lemma 7.5 , the height of the tree is at least, 外部路径长度至少 n! 最坏情况, 平均情况: lgn! lgn!=nlgn LOWER BOUNDS 以关键字为基础的比较,关键字的比较次数的数 量级起码为 O ( nlgn )

DIVIDE-AND-CONQUER SORTING (分而治之的排序)  The Main Ideas dividing a problem into smaller but similar subproblems; that is, of divide and conquer.  Outline void Sortable_list :: sort( ) { if the list has length greater than 1 { partition the list into lowlist, highlist; lowlist.sort( ); highlist.sort( ); combine(lowlist, highlist); }

DIVIDE-AND-CONQUER SORTING  Mergesort (归并排序) We chop the list into two sublists of sizes as nearly equal as possible and then sort them separately. Afterward, we carefully merge the two sorted sublists into a single sorted list.( 将表 分成等长的两个,分别进行排序,然后再合并。

DIVIDE-AND-CONQUER SORTING  Mergesort (归并排序)

Quicksort (快速排序)  We first choose some key from the list for which, we hope about half the keys will come before and half after. Call this key the pivot. (枢轴)  Then we partition the items so that all those with keys less than the pivot come in one sublist, and all those with greater keys come in another. ( 比枢轴小的关键字 记录在一个子表中,比枢轴大的在另一个子表中 )  Then we sort the two reduced lists separately, put the sublists together, and the whole list will be in order. DIVIDE-AND-CONQUER SORTING

 Quicksort (快速排序)

DIVIDE-AND-CONQUER SORTING  Quicksort (快速排序) Tim Dot Eva Roy Tom Kim Guy Amy Jon Ann Jim Kay Ron Jan

Mergesort for Linked Lists (链表的归并排序)  Interface method template void Sortable_list :: merge_sort( ) /* Post: The entries of the sortable_list have been rearranged so that their keys are sorted into non_decreasing order. Uses: Linked List implementation of Chapter 6 and recursive merge sort. */ { recursive_merge_sort(head); }

Mergesort for Linked Lists  Recursive function template void Sortable_list ::recursive_ merge_sort(Node * &sub_list) /* Post: The nodes referenced by sub_list have been rearranged so that their keys are sorted into nondecreasing order. The pointer parameter sub_ list is reset to point at the node containing the smallest key. Uses: The linked List implementation of Chapter 6; the functions divide_ from,merge, and recursive_merge_sort. */ { if (sub_list != NULL && sub_list->next != NULL) {//more than one Node *second_half = divide_from(sub_list); recursive_merge_sort(sub_ list); recursive_merge_sort(second_half); sub_list = merge(sub_list, second_half); }

Mergesort for Linked Lists  Divide Linked List in Half template Node *Sortable_list :: divide_from(Node *sub list) /* Post: The list of nodes referenced by sub_list has been reduced to its first half, and a pointer to the first node in the second half of the sublist is returned. If the sublist has an odd number of entries, then its first half will be one entry larger than its second. Uses: The linkedList implementation of Chapter 6. */ { Node *position, // traverses the entire list *midpoint, // moves at half speed of position to midpoint *second_ half;

Mergesort for Linked Lists  Divide Linked List in Half if ((midpoint = sub_list) == NULL) return NULL; // List is empty. position = midpoint->next; while (position != NULL) { // Move position twice for midpoint 's one move. position = position->next; if (position != NULL) { midpoint = midpoint->next; position = position->next; } second_ half = midpoint->next; midpoint->next = NULL; return second_half; }

Mergesort for Linked Lists Merging two sorted linked lists last_sorted->next = second; last_ sorted = second; second = second->next;

Mergesort for Linked Lists  Merge Function template Node *Sortable_list :: merge(Node *first, Node *second) /* Pre: first and second point to ordered lists of nodes. Post: A pointer to an ordered list of nodes is returned. The ordered list contains all entries that were referenced by first and second. The original lists of nodes referenced by first and second are no longer available. Uses: Methods for Record class; the linked List implementation of Chapter 6. */ { Node *last_sorted; // points to the last node of sorted list Node combined; // dummy first node, points to merged list Last_sorted = &combined;

Mergesort for Linked Lists  Merge Function while (first != NULL && second != NULL) { // Attach node with smaller key if (first->entry entry) { last_sorted->next = first; last_sorted = first; first = first->next; // Advance to the next unmerged node. } else { last_sorted->next = second; last_ sorted = second; second = second->next; } }// After one list ends, attach the remainder of the other. if (first == NULL) last_sorted->next = second; else last_sorted->next = first; return combined.next; }

Mergesort for Linked Lists  Analysis of Mergesort 没有移动, 比较发生在 merge 函数中 最多比较次数不超过两表 的长度。 每一层上表的总长为 n 因此每一层上关键字的比 较次数最多为 n 共有层数约 lgn 比较共约 nlgn

链式结构下的归并排序 速度最快的算法之一,其他链表下的算法难以超 越 花较多的时间将表一分为二 顺序表下的归并排序 在空间效率、时间效率和程序复杂度三个因素中 进行平衡  Analysis of Mergesort

Quicksort for Contiguous Lists (顺序表的快速排序)  The main function Interface method: template void Sortable_list :: quick_sort( ) /* Post: The entries of theSortable list have been rearranged so that their keys are sorted into nondecreasing order. Uses: Contiguous List implementation of Chapter 6, recursive quick sort. */ { recursive_quick_sort(0, count - 1); }

Quicksort for Contiguous Lists  The main function Recursive function: template void Sortable list :: recursive_quick_sort(int low, int high) /* Pre: low and high are valid positions in the Sortable_list. Post: The entries of the Sortable_list have been rearranged so that their keys are sorted into non decreasing order. Uses: Contiguous List implementation of Chapter 6, recursive quick sort,And partition. */ { int pivot_position; if (low < high) { // Otherwise, no sorting is needed. pivot_position = partition(low, high); recursive_quick_sort(low, pivot_position - 1); recursive_quick_sort(pivot_position + 1, high); }

Quicksort for Contiguous Lists  Partitioning the List Algorithm Development

Quicksort for Contiguous Lists  Partitioning the List Algorithm Development

Quicksort for Contiguous Lists  Partitioning the List template int Sortable_list :: partition(int low, int high) /* Pre: low and high are valid positions of the Sortable list, with low <= high. Post: The center (or left center) entry in the range between indices low and high of the Sortable_list has been chosen as a pivot. All entries of the Sortable_list between indices low and high, inclusive, have been rearranged so that those with keys less than the pivot come before the pivot and the remaining entries come after the pivot. The final position of the pivot is returned. Uses: swap(int i, int j) (interchanges entries in positions i and j of a Sortable_list ),the contiguous List implementation of Chapter 6, and methods for the class Record. */ {Record pivot; int i, //used to scan through the list last_small; //position of the last key less than pivot

Quicksort for Contiguous Lists  Partitioning the List swap(low, (low + high)/2); pivot = entry[low]; // First entry is now pivot. last_small = low; for (i = low + 1; i <= high; i++) /* At the beginning of each iteration of this loop, we have the following conditions: If low < j <= last_ small then entry[j].key < pivot. If last_small = pivot.*/ if (entry[i] < pivot) { Last_small = last_small + 1; swap(last_small, i); // Move large entry to right and small to left. } swap(low, last_small); // Put the pivot into its proper position. return last_small; }

( 80 , 100 , 85 , 40 , 75 , 65 , 95 , 82 , 10 , 20 ) if (entry[i] < pivot) { Last_small = last_small + 1; swap(last_small, i); // Move large entry to right and small to left. }

Analysis of Quicksort  Worst-case analysis If the pivot is chosen poorly, one of the partitioned sublists may be empty and the other reduced by only one entry. In this case, quicksort is slower than either insertion sort or selection sort.  Choice of pivot First or last entry: Worst case appears for a list already sorted or in reverse order. Central entry: Poor cases appear only for unusual orders. Random entry: Poor cases are very unlikely to occur.

Analysis of Quicksort  Average-case analysis

HEAPS AND HEAPSORT (堆和堆排序) Complete 2-tree with 31 vertices  If the root of the tree is in position 0 of the list, then the left and right children of the node in position k are in positions 2k + 1 and 2k +2 of the list, respectively. If these positions are beyond the end of the list, then these children do not exist.

HEAPS AND HEAPSORT  Many C++ manuals and textbooks refer to the area used for dynamic memory as the “heap”; this use of the word “heap” has nothing to do with the present definition.  Heapsort is suitable only for contiguous lists.

1.The first entry has the largest key 或 Two kinds of heap {12, 36, 27, 65, 40, 34, 98, 81, 73, 55, 49} 例如 : 是小顶堆 {12, 36, 27, 65, 40, 14, 98, 81, 73, 55, 49} 不是堆 ( 小顶堆 ) ( 大顶堆 ) 2.The first entry has the smallest key

kiki k 2i k 2i+1 we can treat the list as a complete 2-tree Then k 2i is the left child of k i ; k 2i+1 is the right child of k i 。 例如 : Is a heap 14 Isn’t a heap {12, 36, 27, 65, 40, 34, 98, 81, 73, 55, 49}

Heap sort proceeds in two phases. example : rearrange unsorted records into nondecreasing order Build a heap(first is the largest) { 98, 81, 49, 73, 36, 27, 40, 55, 64, 12 } { 12, 81, 49, 73, 36, 27, 40, 55, 64, 98 } Exchange 98 with 12 Insert 12 to the heap from 81 to 64 { 81, 73, 49, 64, 36, 27, 40, 55, 12, 98 } { 40, 55, 49, 73, 12, 27, 98, 81, 64, 36 }

How to build heap ? (build-heap) How to insert an entry ? (insert-heap)

例如 : Is a heap 12 After the exchange of 98 and 12,it isn’t a heap now, We must adjust it.We can think it is a process of inserting 12 to a list which the left and right list is already a heap 比较

The process of building a heap can be implemented by repeating steps of insert-heap Example: the previous order of the list now the left and right list is already a heap , last we insert 98 into the list to satisfy the requirement for a heap

HEAPS AND HEAPSORT

 Main function for heapsort template void Sortable_ list :: heap_ sort( ) /* Post: The entries of the Sortable_ list have been rearranged so that their keys are sorted into nondecreasing order. Uses: The contiguous List implementation of Chapter 6,build heap, and insert heap. */ { Record current; // temporary storage for moving entries int last_ unsorted; // Entries beyond last_unsorted have been sorted. build_ heap( ); // First phase: Turn the list into a heap. for (last_ unsorted = count - 1; last_ unsorted > 0;last_ unsorted--) { current = entry[last_unsorted]; // Extract last entry from list. entry[last _ unsorted] = entry[0]; // Move top of heap to the end Insert_ heap(current, 0, last _ unsorted - 1); // Restore the heap }

HEAPS AND HEAPSORT  Insertion into a heap template void Sortable_ list :: insert_ heap(const Record &current, int low, int high) /* Pre: The entries of the Sortable_list between indices low + 1 and high,inclusive, form a heap. The entry in position low will be discarded. Post: The entry current has been inserted into the Sortable_list and the entries rearranged so that the entries between indices low and high,inclusive, form a heap. Uses: The class Record, and the contiguous List implementation of Chapter 6. */ { int large; // position of child of entry[low] with the larger key large = 2 * low + 1; // large is now the left child of low.

HEAPS AND HEAPSORT  Insertion into a heap while (large <= high) { if (large < high && entry[large] < entry[large +1]) Large++; // large is now the child of low with the largest key. if (current >= entry[large]) break; // current belongs in position low. else { // Promote entry[large] and move down the tree. entry[low] = entry[large]; low = large; large = 2 * low +1; } entry[low] = current; }

Current=

HEAPS AND HEAPSORT  Building the initial heap template void Sortable_ list :: build_ heap( ) /* Post: The entries of the Sortable_list have been rearranged so that it becomes a heap. Uses: The contiguousList implementation of Chapter 6, and insert heap. */ { int low; //All entries beyond the position low form a heap. for (low = count/2 - 1; low >= 0; low--) { Record current = entry[low]; insert_ heap(current, low, count - 1); }

HEAPS AND HEAPSORT  Analysis of Heapsort

HEAPS AND HEAPSORT  Priority Queues DEFINITION : A priority queue consists of entries, such that each entry contains a key called the priority of the entry. A priority queue has only two operations other than the usual creation, clearing, size, full, and empty operations: Insert an entry. Remove the entry having the largest (or smallest) key. If entries have equal keys, then any entry with the largest key may be removed first.

Comparison of Sorting Methods  Use of space  Use of computer time  Programming effort  Statistical analysis  Empirical testing

Pointers and Pitfalls  1. Many computer systems have a general-purpose sorting utility.  2. In choosing a sorting method, take into account the ways in which the keys will usually be arranged before sorting, the size of the application, the amount of time available for programming,the need to save computer time and space, the way in which the data structures are implemented, the cost of moving data, and the cost of comparing keys.

Pointers and Pitfalls  3. Divide-and-conquer is one of the most widely applicable and most powerful methods for designing algorithms. method and program it using recursion.  4. Mergesort, quicksort, and heapsort are powerful sorting methods, more difficult to program than the simpler methods, but much more efficient when applied to large lists.  5. Priority queues are important for many applications. Heaps provide an excellent implementation of priority queues.

Exercise and project 采用顺序存储结构,实现插入排序,归并 排序,快速排序,堆排序,并对这些算法 的实现效率进行比较和分析。