Search code examples
javascriptalgorithmsortingselection-sort

Selection sort algorithm only works when an array without 0 is passed


I am trying to implement a selection sort algorithm. For some reason it only works when I pass an array which does not contain the value 0. I can't seem to figure out why it's doing this.

Here is my solution:

function selectionSort(array) {
  let smallestItem = null;
  let smallestItemIndex = null;
  for(i = 0 ; i < array.length ; i++){
    smallestItemIndex = i;
    for(j = i + 1 ; j < array.length ; j++){
      if(array[smallestItemIndex] > array[j]){
        smallestItem = array[j];
        smallestItemIndex = j;
      } 
    }
    if(smallestItem){
      let temp = array[i];
      array[i] = smallestItem;
      array[smallestItemIndex] = temp;
    }
    smallestItem = null;
  }

Solution

  • This happens because in JS checking: if(smallestItem){ will return true for both 0 and null - this cause to miss the swap in case the smallest item is 0.

    To fix it switch to if(smallestItem == null){