Here's what I would add if I were doing this as a peer review.
Nested For Loops:
Nested for loops are hard to read. As an alternative, split the nested loop into a separate, aptly named function, if possible. Perhaps a function that returns the next item to be swapped with? You would take your nested for loop and move it to a function that would return what is currently temp
if it is there. Then, if there was a return value, you would swap the values. You could even destructure them instead of storing the previous value in a temporary variable: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Also, by moving the for
loop into a different function, you only have to do this numArray[i] = MIN;
if necessary.
Naming:
Your variables are lowercase, lower_case, camelCase, and UPPERCASE. I suggest standardizing on one. For one thing, MIN
looks like a constant to me (from a PHP background), but it is being changed every time in the for
loop. Also, what about improving the names: totalNum
is unclear to me. Without looking beyond the naming is that an accumulator that stores the sum of all the items? temp
could be previousItem
.
Other Items:
- It's typically recommended to declare variables at the top of the function.
j
is declared numerous times.
- You initialize
MIN
at 0
, but then reset it inside of the for
loop. Why not just declare MIN
and not set a value.
A completely different approach:
Finally, I wondered about using Javascript's Array.forEach()
. The following is a completely different perspective, but I thought I would throw it out there for you to consider:
selectionSort();
function selectionSort(){
var originalArray = [4, 34, 2, 5, 12],
sortedArray = [],
lowerSortedIndex;
originalArray.forEach(function(item) {
// Arrow function with implied return:
lowerSortedIndex = sortedArray.findIndex((nextItem) => nextItem >= item);
if (lowerSortedIndex >= 0) {
sortedArray.splice(lowerSortedIndex, 0, item);
} else {
sortedArray[sortedArray.length] = item;
}
});
console.log(sortedArray);
}
The arrow function could be re-written as:
function(nextItem) { return nextItem >= item; })
I wrote it here if you want to play with it: http://codepen.io/bassplayer7/pen/oBxmbW
next_position = 0
\$\endgroup\$O(x²)
\$\endgroup\$my_array.sort()
you could find a javascript library to do it, that should be well-code, more efficient, and without bugs (also saving you some time) \$\endgroup\$