I had an algorithm test.
I was asked Selection sort algorithm to program.
I coded it in javascript and shown to examiner.
But he was not satisfied, he said its too complicated.
I think I have written correctly.
this is the code below,
function selectionSort(inputArray){
var swapElementIndex = 0;
var shouldSwap = false;
var temp = 0;
var minNum = 0;
for(var i = 0;i < (inputArray.length - 1);i++){
minNum = 0;
for(var currentIndex = (i+1); currentIndex < inputArray.length; currentIndex++){
if(inputArray[i] > inputArray[currentIndex]){
if(minNum === 0){ // when first minimum element is found
swapElementIndex = currentIndex;
shouldSwap = true;
minNum = inputArray[swapElementIndex];
}else{// when we have an minimum element
/* further check whether min element is less than the new found [min] element,
if yes set it as min element.
*/
if(minNum > inputArray[currentIndex]){
minNum = inputArray[currentIndex];
swapElementIndex = currentIndex;
shouldSwap = true;
minNum = inputArray[swapElementIndex];
}
}
}
}
if(shouldSwap === true){
temp = inputArray[i];
inputArray[i] = inputArray[swapElementIndex];
inputArray[swapElementIndex] = temp;
shouldSwap = false;
}
}
return inputArray;
}
console.log(selectionSort([1,31,26,4,3,12]));
console.log(selectionSort([5,6,1,2,3,4]));
The output when I run is as follows,
rahul@rahul:~/myPractise/Algo$ node sorting.js
[ 1, 3, 4, 12, 26, 31 ]
[ 1, 2, 3, 4, 5, 6 ]
rahul@rahul:~/myPractise/Algo$
So you can see that its working fine.
Please tell me how can I improve my code
min === 0
would need to be changed. \$\endgroup\$