当前位置: 首页 > news >正文

612.1.004 ALGS4 | Elementary Sorts - 基础排序算法

sublime编辑器写代码,命令行编译
减少对ide的依赖//可以提示缺少什么依赖import
所有示例代码动手敲一遍
Graham's Scan是经典的计算几何算法
shffule 与 map-reduce 有关—— 云计算
知道这些算法在身边切实的应用,对学习动力很有帮助
下一章开始,使用 git进行源代码管理!
先用来做自己的项目管理

Inspiration

计算机思维——不要重复造轮子
零件的通用性——拆分拆分再拆分,专业与分工细致

1.Callback = reference to executable code

1143923-20190311101802016-97778912.png

核心思想是将函数作为实参传递给其他函数
Interface-Java 使我们能够以类型安全的方式使用为任何类型的数据开发的排序算法

Roadmap

对象需要实现Compareble Interface()
这些数据类型具有重新实现compareTo()方法的实例方法

排序实现里与数据类型无关
具体的比较由Comparable 接口处理
1143923-20190311101822635-5416969.png

What I can use —— code

  • Selection Sort | 选择排序
  • Insertion Sort | 插入排序
  • ShellSort | 希尔排序

点击链接可看动画演示

1 Two useful sorting abstrations

Less


private static boolean less(Comparable v, Comparable w)
{   return v.compareTo(w)< 0 ;}

Exchange

//exchange a[i] & a[j]
private static void exch(Comparable[] a,int i ,int j)
{
    Comparable swap = a[i];
    a[i] = a[j];
    a[j] = swap;
}

2.Selection Sort

select the min



1 rules of the game

  • Goal : Sort any type of data

sorting problem
1143923-20190311101832094-819989914.png

real numbers

1143923-20190311101842807-1968988279.png

String

1143923-20190311101848336-397894379.png

Callbacks

key point :passing function as arguments to other function
核心思想是将函数作为实参传递给其他函数
Interface-Java 使我们能够以类型安全的方式使用为任何类型的数据开发的排序算法
1143923-20190311101859823-1600520676.png

Roadmap | 技术路线图 - Callback

public inter face Comparable<Item>
{
    public int compareTo(Item that); // generics method
}

对象需要实现Compareble Interface()
这些数据类型具有重新实现compareTo()方法的实例方法

排序实现里与数据类型无关
具体的比较由Comparable 接口处理

1143923-20190311102115919-1858432870.png

Two useful sorting abstrations

Less


private static boolean less(Comparable v, Comparable w)
{   return v.compareTo(w)< 0 ;}

Exchange

private static void exch(Comparable[] a,int i ,int j)
{
    Comparable swap = a[i];
    a[i] = a[j];
    a[j] = swap;
}

2 Selection Sort | 选择排序

即使数据集已经部分有序,仍需重新遍历一遍
N^2

QuestionDemo-Selection Sort

1143923-20190311102150458-471376514.png

Inner Loop - Selection sort

1143923-20190311102222835-274629351.png

public class SelectionSort
{
    public static void sort(Comparable[] a)
    {
        int N = a.length;
        for (i = 0; i < N;i++)
        {
        int min = i;
        for(int j = i+1; j < N;j++)
            if(less(a[j], a[min]))
                min = j;
         exch(a, i, min);
        }
    }

    private static boolean less(Comparable v,Comparable w)
    {
        return v.compareTo(w) < 0;
    }

    private static void exch (Comparable[] a, int i, int j)
    {
        Comparable swap = a[i];
        a[i] = a[j];
        a[j] = swap;
    }

}

3 Insertion Sort | 插入排序

Move one position at one time
如果左边(比自己)更大,则继续向左互换

QuestionDemo-Insertion Sort

Step1

1143923-20190311102254174-217091959.png

Step2

1143923-20190311102323034-1424322501.png

Inner Loop - Insertion sort

1143923-20190311102351505-1599498032.png


import edu.princeton.cs.algs4.Insertion;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;


public class InsertionSort
{
    public static void sort(Comparable[] a)
    {
        int N = a.length;

        for (int i = 0; i < N; i++)
        {
            for(int j = i; j > 0; j--)
                if(less(a[j],a[j-1]))
                    exch(a,j,j-1);
                else break;
        }
    }

    private static boolean less(Comparable v,Comparable w)
    {
        return v.compareTo(w) < 0;
    }

    private static void exch (Comparable[] a, int i, int j)
    {
        Comparable swap = a[i];
        a[i] = a[j];
        a[j] = swap;
    }

}



public class SortDemo {
    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        Double[] a = new Double[N];
        for (int i = 0; i < N; i++) {
            a[i] = StdRandom.uniform();
        }
        Insertion.sort(a);
        for (int i = 0; i < N; i++) {
            StdOut.println(a[i]);
        }

    }
}

4 ShellSort | 希尔排序

Shell - the name of the creator 1959
Move more than one position at one time // compare to the Insertion Sort
一次移动多个位置
希尔排序,也称递减增量排序算法,是插入排序的一种更高效的改进版本。希尔排序是非稳定排序算法。

希尔排序是基于插入排序的以下两点性质而提出改进方法的: 插入排序在对几乎已经排好序的数据操作时,效率高,即可以达到线性排序的效率 但插入排序一般来说是低效的,因为插入排序每次只能将数据移动一位

Photo:

1143923-20190311102416187-18375732.png

7,3,1 Sort

1143923-20190311102434906-28681648.png

  • Shellsort: which increment sequence to use?

1143923-20190311102453137-1652157929.png

package edu.princeton.cs.algs4;


public class ShellSort{

    public static void sort(Comparable[] a){
        int n = a.length;
     x = 3x+1 increment sequence:  1, 4, 13, 40, 121, 364, 1093, ... 
        int h = 1;
        while (h < n/3) h = 3*h + 1;

        while (h >= 1) {
            //h-sort the array
            // Insertion sort
            for (int i = h; i < n;i++){
                for (j = i; j >= h && less(a[j],a[j-h]); j-= h){
                    exch(a, j, j-h);
                }
            }
            assert isHsorted(a, h); 
            h /=3;//move to next increment,eg. 13,4,1
        }
        assert isHsorted(a, h); 
    }

      /***************************************************************************
    *  Helper sorting functions.
    ***************************************************************************/
    
    // is v < w ?
    private static boolean less(Comparable v, Comparable w) {
        return v.compareTo(w) < 0;
    }
        
    // exchange a[i] and a[j]
    private static void exch(Object[] a, int i, int j) {
        Object swap = a[i];
        a[i] = a[j];
        a[j] = swap;
    }


   /***************************************************************************
    *  Check if array is sorted - useful for debugging.
    ***************************************************************************/
    private static boolean isSorted(Comparable[] a) {
        for (int i = 1; i < a.length; i++)
            if (less(a[i], a[i-1])) return false;
        return true;
    }

    // is the array h-sorted?
    private static boolean isHsorted(Comparable[] a, int h) {
        for (int i = h; i < a.length; i++)
            if (less(a[i], a[i-h])) return false;
        return true;
    }

    // print array to standard output
    private static void show(Comparable[] a) {
        for (int i = 0; i < a.length; i++) {
            StdOut.println(a[i]);
        }
    }

    /**
     * Reads in a sequence of strings from standard input; Shellsorts them; 
     * and prints them to standard output in ascending order. 
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) {
        String[] a = StdIn.readAllStrings();
        ShellSort.sort(a);
        show(a);
    }


}

5 Shuffle - StdRandom.java

Knuth Shuffle
a uniformly random permutation of the input array in linear time.
洗牌

Goal
from

1143923-20190311102550486-126209297.png

to
1143923-20190311102608829-1018527771.png

Code

1143923-20190311102630075-211907261.png


public class StdRandom
{
    public static void shuffle(Object[] a)
    {
        int N = a.length;
        for (int i = 0; i < N; i++);
        {
            int r = StdRandom.uniform(i+1); //StdRandom.uniform 均匀分布  [0,i+1)
                                                        //r = between 0 and i
            exch(a,i,r);
        }
    }
    

}

6 Convex Hull

Graham's Scan
凸包
The convex hull of a set of N points is the smallest perimeter fence enclosing the points

Goal
1143923-20190311102654277-1315524037.png

counterclockwise:逆时针
clockwise:顺时针

mechanical algorithm

1143923-20190311112551395-636545359.png

Computer application
1.motion planning

1143923-20190311112715217-1617893246.png

2.farthest pair

1143923-20190311112747776-1346319504.png

Fact

1143923-20190311112810697-81297335.png

P.S. Polar angle

1143923-20190311112828546-1595400457.png

Graham's Scan 葛立恒扫描

没错 ,就是提出葛立恒数的那位葛立恒
accroding the two facts

Demo

1143923-20190311112846597-1532228275.png

challenge

1143923-20190311112906549-1249873208.png

Implementing ccw(counterclockwise)

what is ccw

1143923-20190311112921547-1052378071.png

** math**

according to the Slope (斜率)
1143923-20190311112946675-1913589614.png

** implement**
1143923-20190311113018283-657213168.png

转载于:https://www.cnblogs.com/Neo007/p/10509568.html

相关文章:

  • 读《构建之法》疑问
  • 如何设置linux支持上传的文件中文不乱吗
  • 致远慧图孙宇辉:出走英特尔的AI眼科野望
  • 为什么你设定的目标最后实现往往都会打折扣?
  • Golang数据结构
  • JSON 自学手册(图文教程)
  • 周工作总结-数据迁移
  • Bootstrap3基础 navbar 导航条 简单示例
  • fio测试nvme性能
  • element ui step组件在另一侧加时间轴显示
  • Windows 下MongoDB复制集配置
  • TJOI2018Party
  • 互联网再迎来割据时代,小程序成为时代宠儿
  • Elasticsearch通关教程(一): 基础入门
  • centos6.5安装和简单实用pyenv
  • Android交互
  • co模块的前端实现
  • CSS中外联样式表代表的含义
  • Docker容器管理
  • download使用浅析
  • E-HPC支持多队列管理和自动伸缩
  • exports和module.exports
  • IndexedDB
  • javascript面向对象之创建对象
  • yii2中session跨域名的问题
  • 初识 webpack
  • 关于List、List?、ListObject的区别
  • 缓存与缓冲
  • 手写一个CommonJS打包工具(一)
  • 智能网联汽车信息安全
  • 大数据全解:定义、价值及挑战
  • 曾刷新两项世界纪录,腾讯优图人脸检测算法 DSFD 正式开源 ...
  • ​软考-高级-系统架构设计师教程(清华第2版)【第20章 系统架构设计师论文写作要点(P717~728)-思维导图】​
  • $Django python中使用redis, django中使用(封装了),redis开启事务(管道)
  • (2)(2.10) LTM telemetry
  • (分布式缓存)Redis分片集群
  • (附源码)springboot车辆管理系统 毕业设计 031034
  • (附源码)ssm航空客运订票系统 毕业设计 141612
  • .net core 6 集成和使用 mongodb
  • .net 简单实现MD5
  • .Net调用Java编写的WebServices返回值为Null的解决方法(SoapUI工具测试有返回值)
  • @EnableAsync和@Async开始异步任务支持
  • @RequestBody的使用
  • [ vulhub漏洞复现篇 ] JBOSS AS 4.x以下反序列化远程代码执行漏洞CVE-2017-7504
  • [2015][note]基于薄向列液晶层的可调谐THz fishnet超材料快速开关——
  • [ffmpeg] aac 音频编码
  • [i.MX]飞思卡尔IMX6处理器的GPIO-IOMUX_PAD说明
  • [leetcode] 3Sum
  • [LeetCode]-Pascal's Triangle III 杨辉三角问题
  • [linux time命令学习篇] time 统计命令执行的时间
  • [Linux]进程创建➕进程终止
  • [MySQL--进阶篇]存储引擎的体系结构、简介、特点、选择
  • [Notice] 朋友们,blog更新http://jiang-hongfei.spaces.live.com
  • [SpringBoot系列]缓存解决方案
  • [SpringMVC] SpringMVC入门