Shortcut for chapter specific information

Sunday, April 24, 2011

2nd - 4th writing of selection sort (C)

#include <stdio.h>
#define    N 10
int main(int c,char* v[])
{
  int A[N] = {3, 5, 7, 1, 2, 6, 8, 9, 10, 0};
  int i,j,imin,t;
  for(j=0;j<N-1;j++){
    imin = j;
    for(i=j+1;i<N;i++)
      if(A[i]<A[imin])
    imin=i;
    if(j!=imin){
      t=A[j];
      A[j]=A[imin];
      A[imin]=t;
    }
  }
  for(i=0;i<N;i++)
    printf("%d ",A[i]);
  printf("\n");
  return 0;
}

This is the version I decided to use at the end.  My 2nd write blews. Why? I failed to apply my mental checking *before* the code is compiled.  I am still too impatient.  My 3rd and 4th are good. 

Lesson: if you already have an algorithm in your head which is refined, when learning a new algorithm, try to apply things you learn from these algorithms.  e.g. I know insertion sort.  Why didn't I use my technique in insertion sort to check my selection sort?
33_P

No comments:

Post a Comment