Skip to content

Conversation

404pnf
Copy link

@404pnf 404pnf commented Jan 27, 2015

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

selectionSort()

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

````js
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 inner for loop.

````js

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

````
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant