oreillymedia / data_structures_and_algorithms_using_javascript

768 stars 407 forks source link

insertionSort(): var outer initialized as 1 or 0? #7

Open 404pnf opened 9 years ago

404pnf commented 9 years ago

I think I found a duplicate prediction in the code.

Code example in the book, Chapter 12.


function insertionSort() {
   var temp, inner;
   for (var outer = 1; outer <= this.dataStore.length-1; ++outer) {
      temp = this.dataStore[outer];
      inner = outer;
      while (inner > 0 && (this.dataStore[inner-1] >= temp)) {
         this.dataStore[inner] = this.dataStore[inner-1];
         --inner;
      }
      this.dataStore[inner] = temp;
   }
}

The var outer initialized as 1. Let's change it to 0. It doesn't affect the function.

Because the inner > 0 in while loop guards against out of bound error in this.dataStore(inner - 1).

Therefore, either we initialize outer with 0 or initialize outer with 1 but drop inner > 0 predict since we don't need it.

I prefer setting outer to 0 at the beginning.


function insertionSort() {
   var temp, inner;
   for (var outer = 0; outer <= this.dataStore.length-1; ++outer) {
      temp = this.dataStore[outer];
      inner = outer;
      while (inner > 0 && (this.dataStore[inner-1] >= temp)) {
         this.dataStore[inner] = this.dataStore[inner-1];
         --inner;
      }
      this.dataStore[inner] = temp;
   }
}
karent commented 9 years ago

I've contacted to author to address your questions about the code examples. Hopefully we'll have an answer to your query shortly.