techInterview Discussion

A part of techInterview.org: answers to technical interview questions.

Your host: Michael Pryor

Find the bug!

I was reading the book, "Find the bug" by Adam Barr.

An interesting concept, where you are shown code and you have to find bugs in it.

Here is one in C:

/* Selection Sort */

void sort (int a [] , int n /*length*/) {

  int current, j, lowestindex, temp;

  for (current = 0; current < n -1; current++) {

    lowestindex = current;

    for (j = current+1; j < n; j++) {

      if (a[j] < a[current]) {
        lowestindex = j;
      }

    } /* inner for */
   
    if (lowestindex != current) {
      temp = a[current];
      a[current] = a[lowestindex];
      a[lowestindex] = tmp;
    }

  } /* outer for*/
}
Myopic
Thursday, March 05, 2009
 
 
j < n
Marck Send private email
Thursday, March 05, 2009
 
 
temp is misspelled tmp (not sure if that's a transcription error).
d Send private email
Thursday, March 05, 2009
 
 
I have the book. It is a transcription error.
NutCase
Thursday, March 05, 2009
 
 
Oh, cute.
d Send private email
Thursday, March 05, 2009
 
 
(It's not j < n.)
d Send private email
Thursday, March 05, 2009
 
 
The loop to find lowestindex always compare to current, and so it will find the last (not lowest) index whose value is less than current.
Proper would be:

lowestindex = current;

    for (j = current+1; j < n; j++) {

      if (a[j] < a[lowestindex]) {
        lowestindex = j;
      }
Radu Cornea Send private email
Thursday, March 05, 2009
 
 
That is right Radu. Subtle, and very plausible.
Myopic
Friday, March 06, 2009
 
 
int n /*length*/ should be int length

but then I'm one of those IfYouFeelTheNeedToWriteACommentTryToRefactorInstead guys ;)

Thursday, March 12, 2009
 
 
I believe it was Myopic's attempt to make the problem a little more clearer. The book does not have the length comment. So, don't judge the book by the errors in the original post, please.
NutCase
Thursday, March 12, 2009
 
 

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
 
Powered by FogBugz