oreillymedia / data_structures_and_algorithms_using_javascript

768 stars 407 forks source link

remove unused var in function selectionSort() #6

Open 404pnf opened 9 years ago

404pnf commented 9 years ago

selectionSort()

Original code example has an unused var temp. We can drop that var.

function selectionSort() {
   var min;
   for (var outer = 0; outer <= this.dataStore.length-2; ++outer) {
      min = outer;
      for (var inner = outer + 1; 
           inner <= this.dataStore.length-1; ++inner) {         
         if (this.dataStore[inner] < this.dataStore[min]) {
            min = inner;  
         }
      }
      swap(this.dataStore, outer, min);
   }
}  

We can drop the var min by moving swap into the if clause in inner for loop. I think this is better because otherwise even if outer and min is the same value, swap is called. It's a bit confusing.


function selectionSort() {
   for (var outer = 0; outer <= this.dataStore.length-2; ++outer) {
      for (var inner = outer + 1; 
           inner <= this.dataStore.length-1; ++inner) {         
         if (this.dataStore[inner] < this.dataStore[outer]) {
            swap(this.dataStore, inner, outer);
         }
      }
   }
}