The practice of programming


Chapter 2 Algorithms and Data Structures

  • Searching
  1. sequential search (linear search):

    easy but the amount of work is directly proportional to the amount of data to be searched

  2. binary search:
    The number of steps is logn, so it's more efficient for a lager array

  • Sorting

  • Libraries

  1. qsort: for example, sort an array of strings:

    /* scmp: string compare of *pl and *p2 */
    int scmp(const void *p1, const void *p2)
    {
    char *v1, *v2;
    v1 = *(char **) p1;
    v2 = *(char **) p2;
    return strcmp(v1, v2) ;
    }
    char astr[N] ;
    
    qsort(str, N, sizeof(str[O]) , scmp);
  2. ANSIC also defines a binary search routine, bsearch.

    /* lookup: use bsearch t o f i n d name i n tab, return index */
    int lookup(char *name, Nameval tab[], i n t ntab)
    {
    Nameval key, anp;
    key.name = name;
    key-value = ; /* unused; anything will do */
    np = (Nameval *) bsearch(&key, tab, ntab, sizeof (tablo]), nvcmp);
    if (np == NULL)
      return -;
    else
      return np-tab;
    }

    As with qsort, the comparison routine receives the address of the items to be compared, so the key must have that type; in this example, we need to construct a fake Nameval entry that is passed to the comparison routine. The comparison routine itself is a function nvcmp that compares two Nameval items by calling strcmp on their string components, ignoring their values:

    /* nvcmp: compare two Nameval names */
      int nvcmp(const void *va, const void *vb){
      const Nameval *a, *b;
      a = (Nameval *) va;
      b = (Nameval *) vb:
      return strcmp(a->name, b->name);
    }
  3. The standard C++  library has a generic algorithm called sort  that guarantees O(n1ogn) behavior.

    int arr[N];
    sort(arr, arr + N); 
  • A Java Quicksort

One big difference from C or Cuis that in Java it is not possible to pass a comparison function to another function; there are no function pointers. Instead we create an interjGace  whose sole content is a function that compares two Objects. For each data type to be sorted, we then create a class with a member function that implements the interface for that data type. We pass an instance of that class to the sort function, which in turn uses the comparison function within the class to compare elements.

  1. defining an interface named Cmp that declares a single member, a comparison function cmp that compares two Objects:

    interface Cmp {
    int cmp(0bject x, Object y){
    }
  2. write comparison functions that implement this interface; for example,

    this class defines a function that compares Integers:

    // Icmp : Integer comparison
    class Icmp implements Cmp {
    public int cmp(Object o1, Object o2)
    {
    int i1 = ((Integer) o1).intValue() ;
    int i2 = ((Integer) o2).intValue() ;
    if ( i1 < i2)
    return -1;
    else if (i1 == i2)
    return 0;
    else
    return 1;
    }
    }
    // Scmp: String comparison
    class Scmp implements Cmp {
    public int cmp(Object o1. Object o2)
    {
    String s1 = (String) o1;
    String s2 = (String) o2;
    return s1.compareTo(s2) ;
    }
    }

    We can sort only types that are derived from Object with this mechanism; it cannot

    be applied to the basic types like i  n t or double. This is why we sort Integers rather

    than int.

    The most significant change is the use of indices left and right, since Java does not

    have pointers into arrays.

  3. // Quicksort. sort: quicksort v[left] . .v[right]
    static void sort(Object[] v, intleft , intright, Cmp cmp)
    {
    int i, last;
    if ( left >= right) // nothing t o do
    return;
    swap(v, left , rand(1eft. right)) ; // move pivot elem
    last = left ; // tov[left]
    for (i = left+l; i <= right; i++) // p a r t i t i o n
    i f (cmp.cmp(v[i], left]) < 0)
    swap(v, ++last, i);
    swap(v, left , last); // restore pivot elem
    sort(v, left , last-1, cmp); // recursively sort
    sort(v, last+l, right, cmp) ; // each part
    } // Quicksort.swap: swap v[i] and v[j]
    static void swap(Object[] v, int i, int j) {
      Object temp;
      temp = v[i];
      v[i] = v[j];
    v[j] = temp;
    }

    The functions sort, swap, and rand, and the generator object rgen are the rnembers of a class Quicksort.

  4. call Quicksort . sort to sort a String array

    String[] sarr = new String[n];
    // fill n elements of sarr...
    Quicksort.sort(sarr, 0, sarr.length-1, new Scmp()); 
  • O-Notation

Purpose: to compare running times and space requirements of algorithms independently of programming language

  • Growing Arrays

typedef struct Nameval Nameval ;
struct Nameval {
char *name;
int value ;
};
struct NVtab {
int nval ; /* current number of values */
int max ; /* allocated number of values */
Nameval tnameval ; /* array of name-value pairs */
} nvtab;
enum { NVINIT = , NVGROW = };
/* addname: add new name and value to nvtab */
int addname (Nameval newname) {
Nameval tnvp ;
if (nvtab.nameva1 == NULL) /* f i r s t time */
nvtab. nameval =
(Nameval *) malloc(NVINIT t sizeof (Nameval )) ;
if (nvtab.nameval == NULL)
return -;
nvtab.max = NVINIT;
nvtab.nval = ;
} else if (nvtab-nval >= nvtab.max) { /* grow */
nvp = (Nameval *) realloc(nvtab.nameval,
(NVGROW*nvtab.max) * sizeof(Nameval));
if (nvp == NULL)
return -;
nvtab.max *= NVGROW;
nvtab.nameval = nvp;
}
nvtab.nameval[nvtab.nval] = newname;
return nvtab.nval++;
}

The call to realloc grows the array to the new size, preserving the existing elements, and returns a pointer to it or NULL if there isn't enough memory.

We can't add elements directly. If the reallocation were to fail, the original array would be lost.

  • Lists
/* newitem: create new item from name and value */
Nameval tnewi tem(char tname, int value){
Nameval *newp;
newp = (Nameval *) emalloc (sizeof (Nameval )) ;
newp->name = name;
newp->value = value ;
newp->next = NULL;
return newp;
}

The simplest and fastest way to assemble  a list is to add each new element to the front.

We can make "apply" more flexible by providing it with an argument to be passed each time it calls the function. So apply has three arguments: the list, a function to be applied to each element of the list, and an argument for that function:

/* apply: execute fn for each element of listp */
void apply (Nameval *listp, void (*fn) (Nameval* , void*) , void *arg)
{
for ( ; listp != NULL; listp = listp->next)
(*fn)(listp, arg); /* call the function */
}

For instance, to destroy a list we must use more care:

for ( ; listp != NULL; l i s t p = next) {
next = listp->next;
/* assumes name is freed elsewhere */
free (listp) ;
}
  • Trees
  • Hash Tables

The idea is to pass the key through a hash function to generate a hash value that will be evenly distributed through a modest-sized integer range.

 

Book Review of “The practice of programming” (Ⅱ)的更多相关文章

  1. Book Review of “The practice of programming” (Ⅳ)

    The practice of programming Chapter 4 Interfaces A good programmer should always be good at designin ...

  2. Book Review of “The practice of programming” (Ⅲ)

    The practice of programming Chapter 3 Design and Implementation In this section, we focus on one kin ...

  3. Book Review of "The Practice of Programming" (Ⅰ)

    The Practice of Programming In the preface, the author illustrates four basic principles of programm ...

  4. 2015年第2本(英文第1本):《The Practice of Programming》

    2015年计划透析10本英文原著,最开始选定的第一本英文书是<Who Moved my Cheese>,可是这本书实在是太短.太简单了,总体的意思就是要顺应变化,要跳出自己的舒适区,全文不 ...

  5. net programming guid

    Beej's Guide to Network Programming Using Internet Sockets Brian "Beej Jorgensen" Hallbeej ...

  6. FRP represents an intersection of two programming paradigms.

    FRP represents an intersection of two programming paradigms. Functional programming Functional progr ...

  7. [转]9个offer,12家公司,35场面试,从微软到谷歌,应届计算机毕业生的2012求职之路

    1,简介 毕业答辩搞定,总算可以闲一段时间,把这段求职经历写出来,也作为之前三个半月的求职的回顾. 首先说说我拿到的offer情况: 微软,3面->终面,搞定 百度,3面->终面,口头of ...

  8. 9个offer,12家公司,35场面试,从微软到谷歌,应届计算机毕业生的2012求职之路

    1,简介 毕业答辩搞定,总算可以闲一段时间,把这段求职经历写出来,也作为之前三个半月的求职的回顾. 首先说说我拿到的offer情况: 微软,3面->终面,搞定 百度,3面->终面,口头of ...

  9. (转)9个offer,12家公司,35场面试,从微软到谷歌,应届计算机毕业生的2012求职之路

    原文:http://www.cnblogs.com/figure9/archive/2013/01/09/2853649.html 1,简介 毕业答辩搞定,总算可以闲一段时间,把这段求职经历写出来,也 ...

随机推荐

  1. Windows下MySQL配置及安全加固总结

    Windows下MySQL配置及安全加固总结 在网管的实际使用过程中,MySQL数据库在安装后的配置及安全加固内容,在客户中逐渐要求越来越高.从反馈的问题看,一般都是由第三方软件公司的软件扫描整个系统 ...

  2. 组合使用QT的资源管理高级功能简化开发过程

    使用 QT 进行团队开发的时候,常常碰到一个问题,就是如何共同管理资源?甚至一个人进行开发的时候如何简化资源的维护,避免无谓的消耗? 如果可以做到在开发的时候,大家把美工做的图片(往往是程序员先自己随 ...

  3. 58、常规控件(1)Floating Action Button-浮动的圆形按钮

               <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xml ...

  4. CNBlog客户端--第二阶段记录

    开始 先给大家看一下我最近的进度,由于最近事比较多,所以这块的精力就相对较少了!但是还是有成绩的!!大家先看效果图吧! 这个优化之后的博客内容显示,还有增加了评论显示页面!! 这个是设置页面,还有一些 ...

  5. c++ 类初始化

    一. 成员初始化列表的位置. 成员初始化列表的位置位于构造函数的函数体和参数表之间.构造函数初始化列表以一个冒号开始,接着是以逗号分隔的数据成员列表,每个数据成员后面跟一个放在括号中的初始化式,初始化 ...

  6. hdu2732 (Leapin' Lizards)

    题目链接:传送门 题目大意:给你 n,m  n:有几行图,m是一个人最多跳m个曼哈顿距离. 给你两张图,第一张图数字为0表示没有柱子,否则有柱子且只能跳出去 x 次(x为当前字符代表的数字) 第二张图 ...

  7. location.assign 与 location.replace的区别

    window.location.assign(url) : 加载 URL 指定的新的 HTML 文档. 就相当于一个链接,跳转到指定的url,当前页面会转为新页面内容,可以点击后退返回上一个页面. w ...

  8. 160812、apache milagro分布式安全认证系统

    java32位.64位及js的代码:http://pan.baidu.com/s/1cqnwuE 一.云链接为中心的软件及需要互联网规模物联网设备 二.利用双线性密码学分发加密操作和分裂的加密参数 三 ...

  9. golang 开发过程中的坑

    1. chan数据读取写入 正常情况下chan读取写入都没有问题,但是如果chan关闭之后会出现问题 所以读取chan数据的时候需要增加chan是否关闭的判断 c := make(chan ) v, ...

  10. delphi --批量添加

    公共批量添加方法 function BatchSQL(DC : TADOConnection; Qry : TADOQuery; StrSQL : TStrings): Boolean; var i ...