Selection Sort Finding(selecting) the smallest element in the loop and swapping it to the starting of the unsorted array. This is best used for finding the smallest element in the array. Let's take an array We will write the outer loop Let's assume the first index of outer loop as smallest(lowest) number Now write the inner loop, and start the inner loop as i+1. Because we need to compare two adjacent elements, hence inner loop starts with i+1 Now after the inner loop, compare the lowest element with current inner loop element. If the inner loop element is lower than lowest element, then reassign lowest number index to j value. After completing the inner loop, check the lowest index value is changed or not If it changed, swap the lowest element index with outer loop index. function selectionSort (arr) { for (let i = 0; i < arr.length; i++) { var lowest = i; for (let j = i + 1; j < arr.length; j++) { ...
Comments
Post a Comment