Skip to content

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

Open

Description

@404pnf

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;
   }
}

Activity

  1. karent commented on Jan 27, 2015

    @karent
    Contributor

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions