Selection sort explanation needed in JS

Hi, Iam trying to sort the numbers in array using selection sort algorithm but I have no idea where the code was going wrong. Please help me.
Here is the code I have written

function selectionSort (array){
  
  let swaps = true;
  let temp;
  
  for(let i=0;i<array.length-1;i++){
  let small = array[i];
  	for (let j= i+1;j<array.length;j++){
    		
    		if(array[j]<small){
        	temp = j;
        	small = array[j]; 
          swaps = false;
        }
    }          

    if(!swaps){
    array[temp]=array[i];
        array[i]=small; 
        
    }
    console.log(array, small, array[temp]); 
  }return array;
}

selectionSort([4,8,9,2,19,14,12]); //[2, 4, 8, 9, 12, 14, 14]

You forgot to reinitialize swaps to true at the beginning of your first for loop, so your logic was confused.

function selectionSort (array){
  
  let swaps = true;
  let temp;
  
  for(let i=0;i<array.length-1;i++){
  let small = array[i];
  swaps = true; //you forgot this line here
  	for (let j= i+1;j<array.length;j++){
    		
    		if(array[j]<small){
        	temp = j;
        	small = array[j]; 
          swaps = false;
        }
    }          

    if(!swaps){
    array[temp]=array[i];
        array[i]=small; 
        
    }
    console.log(array, small, array[temp]); 
  }return array;
}

Thank you so much for help @TonyRatBoy. Happy coding

1 Like