Book Review of “The practice of programming” (Ⅱ)

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 = 0; /* unused; anything will do */
        np = (Nameval *) bsearch(&key, tab, ntab, sizeof (tablo]), nvcmp);
        if (np == NULL)
          return -1;
        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 = 1, NVGROW = 2 };
/* 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 -1;
        nvtab.max = NVINIT;
        nvtab.nval = 0;
    } else if (nvtab-nval >= nvtab.max) { /* grow */
        nvp = (Nameval *) realloc(nvtab.nameval,
            (NVGROW*nvtab.max) * sizeof(Nameval));
        if (nvp == NULL)
            return -1;
        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” (Ⅱ))