Shortcut for chapter specific information

Friday, April 29, 2011

Insertion sort 56-57 (C)

They are all good.  My intention is test out characteristic of C. Listing 1 was the original algorithm.  Whereas Listing 2 and 3 are for insertion sort 56 and 57. I still find even when the for implementation is shortest, it is not as readable as the while implementation.  You can simply compare the C code with the pseudocode and realize that. 

I found listing 2 to be the best compromise.  It still keep the while-loop but shorten the program for 2 lines.  I will adopt it in my code from now on.

Listing 1:

  for(j=1;j<N;j++){
    k=A[j];
    i=j-1;
    while(i>=0&&A[i]>k){
      A[i+1]=A[i];
      i--;
    }
    A[i+1]=k;
  }

Listing 2: Insertion Sort 56
  for(j=1;j<N;j++){
    k=A[j];
    i=j-1;
    while(i>=0&&A[i]>k)
      A[i+1]=A[i--];
    A[i+1]=k;
  }

Listing 3: Insertion Sort 57

  for(j=1;j<N;j++){
    for(k=A[j],i=j-1;i>=0&&A[i]>k;A[i+1]=A[i--]);
    A[i+1]=k;
  }



No comments:

Post a Comment